为什么mocking在nosets多个测试中存在代码后仍然有效?

2024-10-01 02:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的代码测试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()

我还有另一个代码测试,不模仿MyClass.mymethod公司名称:

^{pr2}$

但是,当我做“noestests test_A.py test_B.py”时,它看起来像是在测试完test_A.py并进入test_B.py之后,MyClass.mymethod仍然是模拟的。不知道为什么以及如何避开它。谢谢!在


Tags: 代码frompytestimportself名称none
1条回答
网友
1楼 · 发布于 2024-10-01 02:19:29

行:

MyClass.mymethod = self.m.mock()

确实将MyClass.mymethod()替换为新对象。对MyClass.mymethod的所有后续引用都将指向模拟对象,即使这些引用位于不同的类中。在

您需要的是一种替换MyClass.mymethod()的方法,它只在test_A类中工作。实现这一点的最简单方法是在您的tearDown方法中还原原始的mymethod

^{pr2}$

相关问题 更多 >