我正在比较两个类实例。下面是我的示例测试代码:
from unittest import TestCase
class Dog:
age: int
name: str
def __eq__(self, other):
if not isinstance(other, Dog):
return False
return self.age == other.age and self.name == other.name
class MyTests(TestCase):
def test_compare(self):
d1 = Dog()
d1.age = 1
d1.name = 'dog1'
d2 = Dog()
d2.age = 2
d2.name = 'dog2'
self.assertEqual(d1, d2)
这会产生一个断言错误:
AssertionError: <test.Dog object at 0x0000020444FCA520> != <test.Dog object at 0x0000020444F97D60>
有没有办法直接比较两个实例并获得更有用的错误消息,例如导致断言失败的字段?我发现的唯一方法是直接比较下面的字段。有没有不那么繁琐的方法?
self.assertEqual(d1.age, d2.age)
self.assertEqual(d1.name, d2.name)