python - 在不使用模拟的情况下检查函数是否已在 Python unittest 中调用的规范方法是什么?

标签 python unit-testing testing tdd

如果我有一个类似于下面 1 的类,并且我想测试 bar 函数的各种情况,我如何在不模拟私有(private)函数的情况下完成此操作?换句话说,我如何在 Python 的 unittest 库中实现类似这样的东西:

def test_bar():
    f = Foo()
    f.bar(3)
    expect(self._is_positive_number).toBeCalled()

foo.py

class Foo():
    def bar(self, x):
       if type(x) is not int:
           print('Please enter a valid integer')
           return False

       if x > 0:
           self._is_positive_number()
       elif x == 0:
           self._is_zero()
       else 
           self._is_negative()

    def _is_positive_number(self):
        print('Positive')
        return True

    def _is_zero(self):
        print('Zero')
        return True

    def _is_negative_number(self):
        print('Negative')
        return True

最佳答案

据我所知,如果不模拟私有(private)方法,就无法做到这一点。但是,mock 库(自 3.3 起在标准库中作为 unittest.mock 提供,否则需要单独安装)使这相对轻松:

try:
    # Python 3.3 or later
    import unittest.mock as mock
except ImportError:
    # Make sure you install it first
    import mock

class TestFoo(unittest.TestCase):
    def setUp(self):
        self.f = Foo()

    def test_bar(self):
        with mock.patch.object(self.f, '_is_positive_number') as is_pos:
            self.f.bar(3)
            self.assertTrue(is_pos.called)

关于python - 在不使用模拟的情况下检查函数是否已在 Python unittest 中调用的规范方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23998830/

相关文章:

javascript - 跨测试文件共享模拟

javascript - 如何处理嵌套同步 promise

testing - Wicket 口和AtUnit

java - 使用 Firebase 在 Android Studio 中进行 JUnit 测试

python - Django:使用外键过滤查询不起作用

python - 从字符串中提取温度度数(摄氏度或华氏度)

python - 在 Python 中连接到 MySQL : the safe way?

python - 将发往 pandas.series 的数据转换为干净的数组

c# - 在 UnitTest Mock-DbContext 上使用

maven - 为什么@Ignore 注解不忽略带注解的测试?