UnitTest Python Mock 第一次调用方法,第二次调用照常进行

A.J*_*.J. 6 python unit-testing python-unittest python-unittest.mock

我在嘲笑一种方法。我想在第一次调用时引发异常,但在异常时,我使用不同的参数再次调用该方法,因此我希望第二次调用能够正常处理。我需要做什么?

代码

尝试 1

with patch('xblock.runtime.Runtime.construct_xblock_from_class', Mock(side_effect=Exception)):
Run Code Online (Sandbox Code Playgroud)

尝试 2

with patch('xblock.runtime.Runtime.construct_xblock_from_class', Mock(side_effect=[Exception, some_method])):
Run Code Online (Sandbox Code Playgroud)

在第二次调用时,some_method按原样返回,并且不使用不同的参数处理数据。

Dan*_*Dan 4

class Foo(object):
  def Method1(self, arg):
    pass

  def Method2(self, arg):
    if not arg:
      raise
    self.Method1(arg)

  def Method3(self, arg):
    try:
      self.Method2(arg)
    except:
      self.Method2('some default value')

class FooTest(unittest.TestCase):
  def SetUp(self):
    self.helper = Foo()

  def TestFooMethod3(self):
    with mock.patch.object(self.helper, 'Method2', 
                           side_effect=[Exception,self.helper.Method1]
                           ) as mock_object:
      self.helper.Method3('fake_arg')
      mock_object.assert_has_calls([mock.call('fake_arg'),
                                    mock.call('some default value')])
Run Code Online (Sandbox Code Playgroud)