这个问题不是上述问题的重复,我不是要一个方法来比较实例,而是关于方法assertEqual
,以及它的用途。assertEqual(a, b)
检查是否a == b
并返回true或false,
文件说,
测试第一个和第二个是否相等。如果值不比较
相等,测试将失败。
我在一个简单的类上用assertEqual
运行三个测试,
考试班
class Car:
def __init__(self, name):
self.name = name
测试用例
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: <car.Car instance at 0x7f499ec12ef0> != <car.Car instance at 0x7f499ec12f38>
======================================================================
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: <car.Car instance at 0x7f499ec12fc8> != <car.Car instance at 0x7f499ec12f38>
----------------------------------------------------------------------
Ran 3 tests in 0.000s
FAILED (failures=2)
是否使用“cc>”检查两个实例是否相同?或者我的设置有什么问题吗?为什么
assertEqual
失败了? 最佳答案
你的测试工作很好,而且发现了一个bug。万岁!
你的两辆车可能有相同的名字,但为什么这意味着它们是同一辆车呢?你的代码中没有任何东西能让你这么做。
如果希望如此,请在car类上实现__eq__
:
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
那测试就应该通过了。