为什么mocking在nosetests中存在代码多次测试后仍然有效?
我有以下代码 test_A.py ,它模拟 MyClass.mymethod:
from unittest import main
from mocker import Mocker, MockerTestCase
Class test_A(MockerTestCase):
def setUp(self):
self.m=Mock()
MyClass.mymethod = self.m.mock()
self.m.result(None)
self.m.count(0,None)
self.m.replay()
def test_me(self):
#Do something about MyClass.method
def tearDown(self):
self.m.restore()
self.m.verify()
我还有另一个代码 test_B.py ,它不模拟 MyClass.mymethod:
Class test_B(MockerTestCase):
def setUp(self):
pass
def test_me(self):
#Do something about MyClass.method
def tearDown(self):
pass
但是,当我执行“nosetests test_A.py test_B.py”时,测试后看起来像test_A.py 并进入 test_B.py,MyClass.mymethod 仍然是模拟的。不知道为什么以及如何解决它。谢谢!
I have the following code test_A.py which mocks MyClass.mymethod:
from unittest import main
from mocker import Mocker, MockerTestCase
Class test_A(MockerTestCase):
def setUp(self):
self.m=Mock()
MyClass.mymethod = self.m.mock()
self.m.result(None)
self.m.count(0,None)
self.m.replay()
def test_me(self):
#Do something about MyClass.method
def tearDown(self):
self.m.restore()
self.m.verify()
I also have another code test_B.py which DOES NOT mock MyClass.mymethod:
Class test_B(MockerTestCase):
def setUp(self):
pass
def test_me(self):
#Do something about MyClass.method
def tearDown(self):
pass
However, when I do "nosetests test_A.py test_B.py", it looks like after testing test_A.py and entering test_B.py, MyClass.mymethod is still mocked up. Not sure why and how to get around it. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该行:
确实用新对象替换了
MyClass.mymethod()
。对MyClass.mymethod
的所有后续引用都将指向模拟对象,即使这些引用位于不同的类中。您想要的是一种替换仅在类
test_A
中工作的MyClass.mymethod()
的方法。实现此目的的最简单方法是在tearDown
方法中恢复原始的mymethod
:The line:
really does replace
MyClass.mymethod()
with a new object. All subsequent references toMyClass.mymethod
will be to the mock object, even if those references are in a different class.What you want is a way to replace
MyClass.mymethod()
that only works in classtest_A
. The simplest way to achieve this would be to restore the originalmymethod
in yourtearDown
method: