这个问题不是上述问题的重复,我不是要求一种方法来比较实例,而是要求方法assertEqual
,以及它的目的是什么.
assertEqual(a, b)
检查是否a == b
返回True或False,
文件说,
测试第一和第二是相等的.如果值不相等,则测试将失败.
我assertEqual
在一个简单的课上运行三个测试,
上课时考试
class Car: def __init__(self, name): self.name = name
TestCase
class CarTest(unittest.TestCase): def test_diff_equal(self): car1 = Car('Ford') car2 = Car('Hyundai') self.assertEqual(car1, car2) def test_name_equal(self): car1 = Car('Ford') car2 = Car('Ford') self.assertEqual(car1, car2) def test_instance_equal(self): car1 = Car('Ford') self.assertEqual(car1, car1)
结果是
F.F ====================================================================== FAIL: test_diff_equal (cartest.CarTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "cartest.py", line 10, in test_diff_equal self.assertEqual(car1, car2) AssertionError:!= ====================================================================== FAIL: test_name_equal (cartest.CarTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "cartest.py", line 15, in test_name_equal self.assertEqual(car1, car2) AssertionError: != ---------------------------------------------------------------------- Ran 3 tests in 0.000s FAILED (failures=2)
被assertEqual
用来检查这两个实例中都一样吗?或者我的设置有什么问题?为什么test_name_equal()
失败了?
你的测试工作得非常好,而且发现了一个错误.欢呼!
您的两个Car对象可能具有相同的名称,但为什么这意味着它们是同一辆车?代码中没有任何内容可以做到这一点.
如果您希望如此,请__eq__
在Car类上实现:
def __eq__(self, other): """Return True if other is also a car and has the same name as this one.""" return isinstance(other, Car) and self.name == other.name
那个测试应该通过.