问题描述
我正在模拟以下简化类:
I have the following simplified class I'm mocking:
class myClass(object):
@staticmethod
def A():
#...
def check(self):
#code...
value = self.A()
#more code...
在我的第一次测试中,我只模拟了方法 A
In my first test I mock only the method A
from django.test import TestCase
from mock import MagicMock
import myClass
class FirstTest(TestCase):
def setUp(self):
myClass.A = MagicMock(return_value = 'CPU')
def test(self):
#some tests
myClassObj = myClass()
myClassObj.check()
而在我的第二个测试中,我模拟了整个检查方法:
Whereas in my second test I mock the entire check method:
from django.test import TestCase
from mock import MagicMock
import myClass
class SecondTest(TestCase):
def setUp(self):
myClass.check = MagicMock(return_value = someObject)
def test(self):
#some tests
myClassObj = myClass()
myClassObj.check()
现在我在第一次测试中的断言失败了,因为不是在 check()
中调用 check()
和模拟 A()
,它从我的第二个测试中调用了完全模拟的 check()
.
Now my assertions from my first test fail because, instead of calling check()
and mocking A()
inside check()
, it calls the completely mocked check()
from my second test.
有什么办法可以在测试后清除并设置方法为正常"?我已经尝试了 myClass.check.reset_mock()
,但它似乎没有做任何事情.移动我的测试顺序也没有任何作用.
Is there any way to clear and set the method to be 'normal' after the test? I tried myClass.check.reset_mock()
already, but it doesn't seem to do anything. Moving the order of my tests doesn't do anything either.
我正在使用来自 http://pypi.python.org/pypi 的 python 模拟 1.0b1/模拟/
推荐答案
你可以把函数藏在自己身上,完成后放回去.
You can stash the function away on self and put it back when you're done.
import unittest
from mock import MagicMock
from MyClass import MyClass
class FirstTest(unittest.TestCase):
def setUp(self):
self.A = MyClass.A
MyClass.A = MagicMock(name='mocked A', return_value='CPU')
def tearDown(self):
MyClass.A = self.A
def test_mocked_static_method(self):
print 'First Test'
print MyClass.check
print MyClass.A
class SecondTest(unittest.TestCase):
def setUp(self):
MyClass.check = MagicMock(name='mocked check', return_value=object)
def test_check_mocked_check_method(self):
print 'Second Test'
print MyClass.check
print MyClass.A
if __name__ == '__main__':
unittest.main()
运行此文件会产生以下输出:
Running this file gives the following output:
First Test
<unbound method MyClass.check>
<MagicMock name='mocked A' id='141382732'>
Second Test
<MagicMock name='mocked check' id='141382860'>
<unbound method MyClass.A>
我发现自己现在使用补丁装饰器的次数比 setUp 和 tearDown 多得多.在这种情况下,你可以做
I found myself using the patch decorator a lot more than setUp and tearDown now. In this case you could do
from mock import patch
@patch('MyClass.A')
def test_mocked_static_method(self, mocked_A)
mocked_A.return_value = 'CPU'
# This mock will expire when the test method is finished
这篇关于有什么方法可以将模拟方法重置为其原始状态?- Python Mock - 模拟 1.0b1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!