简体   繁体   English

Python unittest模拟方法在另一个模块中调用时出错

[英]Python unittest mock method which called in another module work error

This is my probject structure, and this problem is a MCVE. 这是我的probject结构,这个问题是MCVE。

  • wrx_test wrx_test
    • use_mock use_mock
    • init .py 初始化 .py
    • A.py A.py
    • B.py B.py
    • use_mock.py use_mock.py

A.py A.py

def do_something():
    print 'a i do something'
    return 10

B.py B.py

from wrx_test.use_mock.A import do_something
class B(object):
    def b_do_something(self):
        x = do_something()
        print x
        return x

use_mock.py use_mock.py

from mock import patch
from unittest import TestCase

from wrx_test.use_mock.B import B


class TestUseMock(TestCase):
    @patch('wrx_test.use_mock.A.do_something')
    def test_use_mock(self, mock_do_something):
        from wrx_test.use_mock.A import do_something

        mock_do_something.return_value = 4
        print do_something()
        B().b_do_something()

In use_mock.py i set the mocked method return_value equal 4, but it doesn't work as excepted. 在use_mock.py中,我将模拟方法return_value设置为4,但是它不能正常工作。 How can i make the mocked method A.do_something work correctly in module B, and i wonder now the reason. 我如何才能使A.do_something方法A.do_something在模块B中正常工作,现在我想知道原因。

result 结果

a i do something
10 

I think the way mock works is that you designate a function in a module to be replaced by your mock when this function is used in another call. 我认为模拟的工作方式是您在模块中指定一个函数,以便在另一个调用中使用该函数时将其替换为模拟。 Example: patch('A.do_something) would mean that if you test a function that internally calls A.do_something(), it will be replaced inside that call. 例如:patch('A.do_something)意味着如果您测试一个内部调用A.do_something()的函数,它将在该调用内被替换。 But here you're directly executing that function. 但是在这里,您直接执行该功能。 I also don't see any useful case for doing this. 我也没有看到任何有用的案例。 If you want to call the mock directly, do: mock_do_something() 如果要直接调用模拟,请执行以下操作:mock_do_something()

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

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