【发布时间】:2021-08-09 05:39:33
【问题描述】:
我正在尝试使用@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
【问题讨论】:
-
模拟附件服务是如何进入你的 postEventHandler 的?必须使用 Spring 的机制来创建 handler,否则无法在适用的地方注入 mocks。
标签: java spring junit5 spring-boot-test