简体   繁体   English

Python unittest 何时测试值或 object 相等

[英]Python unittest when to test for value or object equality

I have the following code that I'm testing.我有以下正在测试的代码。

main.py

import helpers

def do_something(some_arg):
    ...
    return helpers.help_do_something(some_arg)

test_main.py

import unittest
from unittest import mock

class TestDoSomething(unittest.Testcase):
    @mock.patch('path.to.patch')
    def setUp(self, *_):
        import main
        self.main = main

    @mock.patch('main.helpers')
    def test_0_1(self, helpers_mock):
        ret = self.main.do_something('test_arg')
        self.assertIs(ret, helpers_mock.help_do_something.return_value)

When I'm testing the return value of do_something my instinct is telling me that the comparison should be asserting object equality, not value equality.当我测试do_something的返回值时,我的直觉告诉我,比较应该断言 object 相等,而不是值相等。 Am I correct in thinking this?我这样想对吗? I'm having a difficult time articulating why this should be the case.我很难解释为什么会这样。

More generally, when should we be testing for object equality versus value equality in unit testing?更一般地说,我们什么时候应该在单元测试中测试 object 相等与值相等?

It's unlikely that you want to use object equality here.您不太可能在此处使用 object 相等性。 The only case would be, if your mock function would return the same object (not an equally valued object) as the function you are testing, which could only happen if they either take it from input parameters (which is not the case here) or from some common pool of objects.唯一的情况是,如果您的模拟 function 将返回与 function 相同的 object (不是同等价值的对象),那么您正在测试的情况(这不会发生)来自一些常见的对象池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM