python - 为什么我的简单 __eq__ 实现给出了 AssertionError?

标签 python unit-testing python-3.x operator-overloading equality

我正在尝试在 Python 3.3 中实现一个标准的相等运算符,遵循其他问题的代码示例。我收到一个断言错误,但我无法弄清楚哪里出了问题。我在这里错过了什么?

class RollResult:
    def __init__(self, points, unscored_dice):
        self.points = points
        self.unscored_dice = unscored_dice

    def __eq__(self, other):
        return (self.points == other.points and self.unscored_dice == other.unscored_dice)

这是测试。许多其他测试都通过了,所以基本设置是正确的。这是我对该类的第一次测试,我以前从未尝试过单元测试相等性重载,所以它也可能是测试的错误。

class TestRollResultClass(unittest.TestCase):
    def test_rollresult_equality_overload_does_not_test_for_same_object(self):
        copy1 = RollResult(350,2)
        copy2 = RollResult(350,2)
        self.assertNotEqual(copy1,copy2)

结果:

AssertionError: <greed.RollResult object at 0x7fbc21c1b650> == <greed.RollResult object at 0x7fbc21c1b650>                                        

最佳答案

您的 __eq__() 似乎工作正常。您正在使用 assertNotEqual(),如果两个参数相等,这将引发 AssertionError。您为断言中使用的每个 RollResult 对象提供了相同的参数,因此它们相等,因此失败。

看起来您要么想使用 assertEqual(),要么更改它,使 copy1copy2 的构造不同。

关于python - 为什么我的简单 __eq__ 实现给出了 AssertionError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19938157/

相关文章:

python - 如何在不知道子类名称的情况下访问 django 中对象的子类?

python - 识别复数

unit-testing - 将模拟框架用于其他东西然后进行单元测试?

unit-testing - 在测试中覆盖 Go 方法

python - PIL 类型错误 : text() has multiple values for argument 'font'

python - 如何编写sql来更新目标表中仅给出一条记录的某些字段

java - TestNG:如何跳过某些测试的@BeforeMethod 调用

python-3.x - sns.distplot 正在为唯一的正变量绘制负值

python - 如何通过python更准确地聚合数据框中的值?

python - 将 Python 图导出为 KML