模拟存储库返回 null - Springboot JUnit Mockito

问题描述

我正在尝试使用我的存储库 EmpresaRepository 中的保存,但它返回 null,这是我的存储库 heres my repository and this is my test

And this is the output

解决方法

这是预期的行为。

通过使用 @MockBean,您可以创建 EmpresaRepository 的 Mock 并将其添加到 ApplicationContext 中。 这意味着您执行模拟的 ::save() 方法,该方法默认返回 null

经验法则:永远不要嘲笑你想测试的东西。

如果您用 @MockBean 替换 Autowired 注释,测试应该可以工作。


顺便说一句。 请不要发布您的代码的屏幕截图。在不同的选项卡之间切换很烦人,而且我无法复制您的部分代码。