Mockito 在同一 class 中使用来自其他测试方法的方法存根
Mockito uses method stubbing from other test method in the same class
我正在尝试测试快乐路径和异常场景的方法。
我的 class 看起来像这样
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 中调试测试。我正在获取异常测试方法的“模拟数据”。似乎是对该方法的模拟没有为第二种方法重置。
有没有办法从以前的测试方法中刷新方法mocking/stubbing?
首先我会认为这是一个错误。但是你可以手动重置 mocks
@Before
public void resetMock() {
Mockito.reset(anotherClass);
}
我正在尝试测试快乐路径和异常场景的方法。 我的 class 看起来像这样
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 中调试测试。我正在获取异常测试方法的“模拟数据”。似乎是对该方法的模拟没有为第二种方法重置。 有没有办法从以前的测试方法中刷新方法mocking/stubbing?
首先我会认为这是一个错误。但是你可以手动重置 mocks
@Before
public void resetMock() {
Mockito.reset(anotherClass);
}