@MockBean 返回空对象

bha*_*vya 0 java spring junit5 spring-boot-test

我正在尝试使用@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", "");
       }
    }
Run Code Online (Sandbox Code Playgroud)
    @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);
             ...
           }
    }
Run Code Online (Sandbox Code Playgroud)

附件服务没有被模拟它返回 null

Mar*_*nik 5

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

它真的@MockBean创建了一个模拟(内部使用的Mockito)和看跌期权这个bean到应用程序上下文,以便可以将可用于注射剂等

但是,作为程序员,你有责任指定当你调用一个或另一个方法时,你期望从这个模拟返回什么。

所以,假设你AttachementService有一个方法String foo(int)

public interface AttachementService { // or class 
   public String foo(int i);
}
Run Code Online (Sandbox Code Playgroud)

您应该在 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);
   }
Run Code Online (Sandbox Code Playgroud)

如果您不指定期望值并且您的被测代码foo在某个时候调用,则此方法调用将返回null

  • 即使添加上面的行之后;当我运行 testCase 时,attachmentService 在handlePostBeforeCreate 中为空 (3认同)
  • 正如@bhavya所说,你的答案并不能真正帮助修复服务为空的问题。 (2认同)
  • 根本没有帮助回答,好像他根本没有读过这个问题哈哈 (2认同)

小智 0

我遇到了类似的问题:我在模拟 bean 中也有 null,但只有当我一次运行多个测试时(例如,当我运行“mvn clean package”时)

如果这是你的情况(或者如果是某人的情况,他会看到这篇文章),那么这种情况可以通过在你运行的每个测试类上注释 @DirtiesContext 来解决