3

我有以下代码 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 仍然是模拟的。不知道为什么以及如何解决它。谢谢!

4

1 回答 1

3

该行:

MyClass.mymethod = self.m.mock()

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

您想要的是一种MyClass.mymethod()仅在课堂上有效的替换方法test_A。实现此目的的最简单方法是mymethod在您的tearDown方法中恢复原始内容:

Class test_A():
    def setUp(self):
        self.originalMyMethod = MyClass.mymethod
        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.mymethod

    def tearDown(self):
        self.m.restore()
        self.m.verify()
        MyClass.mymethod = self.originalMyMethod
于 2011-12-14T05:29:04.487 回答