代码之家  ›  专栏  ›  技术社区  ›  Phil Gunning

使用嵌套函数更改进行模拟测试

  •  0
  • Phil Gunning  · 技术社区  · 2 年前

    我正在将测试添加到一个管道项目中,代码已经编写并正在生产中,因此无法更改它以适应测试。

    简单地说,如果我有这样一个函数:

    def other_foo():
        return 1
    
    def foo():
        res = other_foo()
        return res
    

    在实用性方面 other_foo 调用将返回各种响应,但对于测试,我想创建一个固定的响应来测试 foo

    所以在我的测试中,我想对 其他\u foo 共2页。我的测试评估是:

    def test_foo():
        # some mocking or nesting handle here for other_foo
        res = foo()
        assert res == 2
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Cyrille Pontvieux    2 年前

    使用 patch 装饰器来自 unitest.mock 并修补模块局部变量。

    from your.module import foo
    from unitest.mock import patch
    
    @patch('your.module.other_foo')
    def test_foo(mock_other_foo):
        mock_other_foo.return_value = 3
        assert foo() == 3
        mock_other_foo.return_value = 42
        assert foo() == 42
    

    您可以找到更多信息 here there