unit-testing - 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 中调试测试。我正在获取异常测试方法的“模拟数据”。似乎对该方法的嘲笑没有为第二种方法重置。有没有办法从以前的测试方法中刷新方法模拟/存根?
解决方案
首先,我认为这是一个错误。但是您可以手动重置模拟
@Before
public void resetMock() {
Mockito.reset(anotherClass);
}
推荐阅读
- python - Flask (flask-restful) 和 MySQLdb (PyMySQL) 的奇怪并发问题
- python - AWS Lambda Opencv(“无法导入模块'lambda_function':libgthread-2.0.so.0:无法打开共享对象文件:没有这样的文件或目录”)
- angular - 从 Angular 11 中的 Spring Boot 响应中获取标头
- java - 当一个元素发生异常时,如何处理 Java 8 流列表中的剩余元素?
- python - Matplotlib 3.3.2 中不提供 CenteredNorm 吗?
- javascript - 加载更多 | Ajax Wordpress 和过滤器
- vuejs2 - 使用图像时的ckeditor布局问题
- r - 根据列中的第一个值过滤数据框列表
- flutter - 我无法访问 providerScope 以允许我的导航路线依赖于未来
- graphics - 为什么点云中的真正点或主骨架附近有很多不相关的点?