我有一段代码放在这样的模块中:
我的工人.py:

from gevent import sleep

class MyWorker(object):
  def run(self):
    for _ in range(10):
      do_something()
      sleep(1)

然后我想在嘲笑睡眠的同时测试一下。我尝试了多种方法,但都失败了。我认为有一种方法是可行的:
from mock import patch
from x.y.z.MyWorker import MyWorker

class TestWorker(unitest.testCase):
  def Test_my_worker(self):
    with patch('x.y.z.MyWorker.sleep'):
      a = MyWorker()
      a.run()

最佳答案

我又试了几次,结果发现很容易修复:
from x.y.z.MyWorker import MyWorker更改为from x.y.z.MyWorker import MyWorker, sleep,或者您可以执行from x.y.z.MyWorker import *并且所有单元测试都可以工作。上面的评论给了我这个想法。
这就是我最终要做的:

from x.y.z.MyWorker import MyWorker, sleep

Class TestMyWorker(unittest.TestCase):

  def setUp(self):
    self.patcher = patch('x.y.z.MyWorker.sleep')
    self.patcher.start()

  def tearDown(self):
    self.patcher.stop()

  def Test_my_worker_success():
    MyWorker().run()

  def Test_my_worker_fail():
    ...

09-05 23:51