Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@MockBean is returning null object

I am trying to use @MockBean; java version 11, Spring Framework Version (5.3.8), Spring Boot Version(2.5.1) and 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 is not being mocked it gives null in return

like image 478
bhavya Avatar asked Aug 17 '26 03:08

bhavya


1 Answers

As @johanneslink said, the problem is this line:

PostEventHandler postEventHandler = new PostEventHandler();

Spring won't inject anything into your PostEventHandler bean if you manually construct it.

The following should make your test work, note the @Autowired postEventHandler. :)

@SpringBootTest
public class PostEventHandlerTest {

    @MockBean
    private AttachmentService attachmentService;

    @Autowired
    PostEventHandler postEventHandler;
    
    @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.handlePostBeforeCreate(post);
        
        verify(attachmentService, times(1)).storeFile("abc.txt", "");
   }
}
like image 60
criztovyl Avatar answered Aug 19 '26 17:08

criztovyl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!