java - Spring Boot 测试中的严格@MockBean
问题描述
我正在开发一个 Spring Boot 应用程序。对于我的常规服务类单元测试,我可以使用 扩展我的测试类MockitoExtension
,并且模拟是严格的,这就是我想要的。
interface MyDependency {
Integer execute(String param);
}
class MyService {
@Autowired MyDependency myDependency;
Integer execute(String param) {
return myDependency.execute(param);
}
}
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@Mock
MyDependency myDependency;
@InjectMocks
MyService myService;
@Test
void execute() {
given(myDependency.execute("arg0")).willReturn(4);
myService.execute("arg1"); //will throw exception
}
}
在这种情况下,将引发异常并显示以下消息(已编辑):
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'execute' method:
myDependency.execute(arg1);
- has following stubbing(s) with different arguments:
1. myDependency.execute(arg0);
此外,如果从未使用过存根,则会出现以下内容(已编辑):
org.mockito.exceptions.misusing.UnnecessaryStubbingException:
Unnecessary stubbings detected.
Clean & maintainable test code requires zero unnecessary code.
Following stubbings are unnecessary (click to navigate to relevant line of code):
1. -> at MyServiceTest.execute()
但是,当我@MockBean
在集成测试中使用时,不存在任何严格的行为。相反,存根方法返回 null 因为存根“失败”静默。这是我不想要的行为。当使用意外的参数时,最好立即失败。
@SpringBootTest
class MyServiceTest {
@MockBean
MyDependency myDependency;
@Autowired
MyService myService;
@Test
void execute() {
given(myDependency.execute("arg0")).willReturn(4);
myService.execute("arg1"); //will return null
}
}
有什么解决方法吗?
解决方案
推荐阅读
- python-3.x - Python - 如何减去两个日期字符串并将结果转换为毫秒
- java - Java/Swing 将输入从多个 JTextField 保存到文件中
- java - OpenJDK Panama Vector API jdk.incubator.vector 没有为 Vector 点积提供改进的结果
- python - Tensorflow Python 无法在 windows server 2012 R2 上加载本机 TensorFlow 运行时
- javascript - emailjs.send email 仅在调试模式下工作
- iso - HEIF 中对任意编解码器的平台支持
- laravel - Laravel:每天求和(分组日期),然后保留空行的日期
- delphi - 如何在设计时拼接 Delphi FireDAC 查询代码
- lotus-notes - Lotus Notes X-Frame 选项
- python-3.x - 如何在 tsv 文件中存储字符串键和 numpy 数组值的字典?