首页 > 解决方案 > Mockito 使用来自同一类中其他测试方法的方法存根

问题描述

我正在尝试测试快乐路径和异常场景的方法。我的课看起来像这样

class MyClass
{
  @Autowired
  AnotherClass anotherClass;

  public Object myMethod() throws MyException
  {
     try{
       //DO SOME STUFF
       anotherClass.anotherMethod();
     }
     catch(Exception e)
     {
        throw MyException(e);
     }
  }
}

我正在像这样测试上面的 myMethod 。

@RunWith(MockitoJUnitRunner.class)
class MyClassTest
{
   @Mock
   AnotherClass anotherClass; 
   @InjectMocks
   MyClass myClass;

   @Test
   public void myMethodTest()
   {
      when(anotherClass.anotherMethod()).thenReturn("Mocked data");

      myClass.myMethod();
   }
   
   @Test(expected=MyException.class)
   public void myMethodExpTest()
   {
      when(anotherClass.anotherMethod()).thenThrow(MyException.class);

      myClass.myMethod();
   }
}

当我使用 Jacoco 检查代码覆盖率时,它没有覆盖异常捕获块。我尝试在我的 Eclipse IDE 中调试测试。我正在获取异常测试方法的“模拟数据”。似乎对该方法的嘲笑没有为第二种方法重置。有没有办法从以前的测试方法中刷新方法模拟/存根?

标签: unit-testingjunitmockito

解决方案


首先,我认为这是一个错误。但是您可以手动重置模拟

@Before
public void resetMock() {
  Mockito.reset(anotherClass);
}

推荐阅读