@MockBean返回空对象

我正在尝试使用@MockBean;java 版本 11、Spring 框架版本 (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);
             ...
           }
    }

附件服务没有被模拟它返回 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


以上是@MockBean返回空对象的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>