Я пытаюсь использовать @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 для создания обработчика, иначе он не сможет внедрить макеты в соответствующих местах.