Skip to main content
 首页 » 编程设计

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

2024年10月24日7thcjp

我在模拟一个方法。我想在第一次调用时引发异常,但在异常时,我用不同的参数再次调用该方法,所以我希望第二次调用能够正常处理。我需要做什么?

代码

尝试1

with patch('xblock.runtime.Runtime.construct_xblock_from_class', Mock(side_effect=Exception)): 

尝试2

with patch('xblock.runtime.Runtime.construct_xblock_from_class', Mock(side_effect=[Exception, some_method])): 

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

请您参考如下方法:

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')])