我正在尝试使用@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
我想你误解了mock的用法。
确实,@MockBean
创建了一个mock(在内部使用Mockito),并将这个bean放在应用程序上下文中,以便它可以用于注入等。
然而,作为一个程序员,你有责任指定当你在这个mock上调用一个或另一个方法时,你期望从这个mock返回什么。
假设你的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
我遇到了一个类似的问题:我在mock bean中也有null,但只有当我一次运行几个测试时(例如,当我运行"mvn clean package")
如果这是你的情况(或者如果是别人的情况,谁会看到这篇文章),那么这种情况可能会通过注释@DirtiesContext来解决你运行的每个测试类
正如@johanneslink所说,问题出在这一行:
PostEventHandler postEventHandler = new PostEventHandler();
如果你手动构建PostEventHandler
bean, Spring不会向它注入任何东西。
下面应该使您的测试工作,注意@Autowired
postEventHandler
。:)
@SpringBootTest
public class PostEventHandlerTest {
@MockBean
private AttachmentService attachmentService;
@Autowired
PostEventHandler postEventHandler;
@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.handlePostBeforeCreate(post);
verify(attachmentService, times(1)).storeFile("abc.txt", "");
}
}