java - @MockBean 正在返回空对象
问题描述
我正在尝试使用@MockBean;java 版本 11、Spring Framework 版本 (5.3.8)、Spring Boot 版本(2.5.1) 和 Junit Jupiter (5.7.2)。
@SpringBootTest
public class PostEventHandlerTest {
@MockBean
private AttachmentService attachmentService;
@Test
public void handlePostBeforeCreateTest() throws Exception {
Post post = new Post("First Post", "Post Added", null, null, "", "");
Mockito.when(attachmentService.storeFile("abc.txt", "")).thenReturn(new Attachment());
PostEventHandler postEventHandler = new PostEventHandler();
postEventHandler.handlePostBeforeCreate(post);
verify(attachmentService, times(1)).storeFile("abc.txt", "");
}
}
@Slf4j
@Component
@Configuration
@RepositoryEventHandler
public class PostEventHandler {
@Autowired
private AttachmentService attachmentService;
@Autowired
private PostRepository postRepository;
public void handlePostBeforeCreate(Post post) throws Exception {
...
/* Here attachmentService is found null when we execute above test*/
attachmentService.storeFile(fileName, content);
...
}
}
attachmentService 没有被嘲笑,它给出了 null 作为回报
解决方案
我认为您误解了 Mocks 的用法。
确实@MockBean
创建了一个模拟(内部使用 Mockito)并将这个 bean 放到应用程序上下文中,以便它可以用于注入等。
但是,作为程序员,您有责任指定当您在其上调用一种或另一种方法时,您希望从该模拟返回什么。
所以,假设你AttachementService
有一个方法String foo(int)
:
public interface AttachementService { // or class
public String foo(int i);
}
您应该在 Mockito API 的帮助下指定期望:
@Test
public void handlePostBeforeCreateTest() throws Exception {
// note this line, its crucial
Mockito.when(attachmentService.foo(123)).thenReturn("Hello");
Post post = new Post("First Post", "Post Added", null, null, "", "");
PostEventHandler postEventHandler = new PostEventHandler();
postEventHandler.handlePostBeforeCreate(post);
verify(attachmentService, times(1)).storeFile("", null);
}
如果您不指定期望并且如果您的被测代码foo
在某个时候调用,则此方法调用将返回null
推荐阅读
- azure - Azure-使用 CLI 获取刷新令牌过期时间
- c# - 使用 Linq First Group 特定的 Column 值,然后从第二列获取值的平均值
- c++ - Visual Studio 19 中的命令行输入和输出
- python - 熊猫:如何删除系列中的非字母数字列
- c# - 如何在 SQL 数据库表 C# 中的数据更改时更新(通知)DataGridView
- grafana - Grafana:plugin.json 中的跳过数据查询
- plc - Codesys 2.3 - wago 750-842 - I/O
- bash - Bash 脚本在执行后不退出 SSH 主机
- jquery - HTML5 音频自动播放在 chrome 中不起作用
- node.js - express-session 在使用 Angular 刷新时删除会话