こんにちは。Yuinaです。
今日は、TDD駆動開発(著者:KentBeck)をPythonで書き換えています。
あんまり一般的ではありませんが、学習目的で下記のようなコードを書いています。お許しください。
MoneyTest.py
import unittest
from dollar import Dollar
class TestMoney(unittest.TestCase):
def test_equality(self):
# Dollarクラスのインスタンスを作成し、インスタンス変数の値を設定
five = Dollar(5)
# クラス変数の値をインスタンス変数の値と同じに設定
Dollar.amount = 5
# インスタンス変数とクラス変数が等しいかテスト
self.assertEqual(five.amount, Dollar.amount)
# クラス変数の値を変更し、等しくないことをテスト
Dollar.amount = 6
self.assertNotEqual(five.amount, Dollar.amount)
if __name__ == '__main__':
unittest.main()
test.py
class Dollar:
amount = 0 # これはクラス変数
def __init__(self, amount):
self.amount = amount # これはインスタンス変数
def times(self, multiplier):
return Dollar(self.amount * multiplier)
def __eq__(self,other):
if isinstance(other, Dollar):
return self.amount == other.amount
return False
ありがとうございました。