我正在尝试为快乐路径和异常场景测试一种方法。 我的班级是这样的
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 中调试测试。我正在获取异常测试方法的“模拟数据”。似乎对该方法的嘲笑并未为第二种方法重置。 有没有办法从以前的测试方法中刷新方法模拟/存根?
答案 0 :(得分:0)
首先我会认为这是一个错误。但是您可以手动重置模拟
@Before
public void resetMock() {
Mockito.reset(anotherClass);
}