java - @MockBean 返回空对象

标签 java spring junit5 spring-boot-test

我正在尝试使用@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

最佳答案

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

@MockBean 确实创建了一个模拟(内部使用 Mockito)并将这个 bean 放到应用程序上下文中,以便它可用于注入(inject)等。

但是,作为程序员,您有责任指定当您在其上调用一种或另一种方法时,您期望从该模拟返回什么。

因此,假设您的 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

关于java - @MockBean 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68707300/

相关文章:

java - 从 EntityManagerFactory 创建 EntityManager

java.lang.ClassCastException : Z cannot be cast to java. lang.String

java - exec() 问题,未打开文件

spring - 存储库剩余资源无法嵌入自引用对象

java - Junit 如何执行测试用例?

java - Spring Batch 在有效的 csv 标题之前写入行

java - Spring Boot 应用程序在作为 jar 运行时看不到 bean

Spring-Data-Cassandra SchemaAction 不工作

java - 如何为显式抛出的异常编写 junit 测试

java - 如何在 JUnit5 中测试引发异常?