assertEqual(a, b)
检查是否 a == b
并返回 True 或 False,
文档说,
Test that first and second are equal. If the values do not compare equal, the test will fail.
我在一个简单的类上使用 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)
assertEqual
是否用于检查两个实例是否相同?或者我的设置有什么问题吗?为什么 test_name_equal()
失败了?
最佳答案
您的测试工作绝对正常,但发现了一个错误。欢呼!
您的两个 Car 对象可能具有相同的名称,但为什么这意味着它们是同一辆车?您的代码中没有任何内容可以做到这一点。
如果您希望如此,请在 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
然后该测试应该通过。
关于python - Python UnitTest 中的 assertEqual 应该做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34728569/