【问题标题】:@MockBean is returning null object@MockBean 正在返回空对象
【发布时间】: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


【解决方案1】:

我认为你误解了 Mocks 的用法。

@MockBean 确实创建了一个 mock(内部使用 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

【讨论】:

  • 即使添加了上面的行;当我运行 testCase 时,附件服务在 handlePostBeforeCreate 中为空
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-15
  • 2021-09-03
  • 2014-06-08
相关资源
最近更新 更多