在单元测试中使用 assertTrue(==) 与 assertEqual

Using assertTrue(==) vs assertEqual in unittest

在 Python unittest 模块中,在以下情况下使用 assertTrue()assertEqual() 有什么优点或缺点吗?

self.assertTrue(a == b)
self.assertEqual(a, b)

始终使用 assertEqual(),因为它 自定义失败输出

该方法委托给各种帮助器方法来向您展示,例如,两个字符串或两个列表在断言失败时如何不同,前提是两个参数的类型匹配并且注册了特定于类型的帮助器方法。

assertTrue() 只能告诉您断言失败,而不能告诉您原因。

来自assertEqual() documentation:

In addition, if first and second are the exact same type and one of list, tuple, dict, set, frozenset or str or any type that a subclass registers with addTypeEqualityFunc() the type-specific equality function will be called in order to generate a more useful default error message (see also the list of type-specific methods).

只有在没有更具体的断言可用时才使用 assertTrue()

如果您想检查 True 以外的值,请选择 assertEqual 以获得有意义的错误消息。在我看来,当您定义预期部分与要检查的值相比时,它也更具可读性。

如果要检查 assertTrue(user.hasAdminRole())

等真布尔结果,请选择 assertTrue 而不是 assertEqual