首页 > 解决方案 > @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 作为回报

标签: javaspringjunit5spring-boot-test

解决方案


我认为您误解了 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


推荐阅读