Search code examples
spring-bootjunitmockitospring-testspring-boot-test

What is difference here - @Autowired and @MockBean


I was writing unit tests for our services classes in spring boot project. Where tests were properly running when I'am autowiring the class which am testing and it fails when I use @MockBean insead of @Autowire.

@SpringBootTest
class SignupServiceTest {

  @Autowired SignupService signupService;

  @MockBean DSService dsService;

  @MockBean SignupHelper signupHelper;

  @MockBean SessionHelper sessionHelper;

  @MockBean CommonService commonService;

Can somehelp help me with difference and why @MockBean is failing. Also is there a way to mock methods of autowired class(Current class) in mockito.


Solution

  • A @SpringBootTest is a test that actually starts up a Spring container along with the beans of the application.

    @Autowired fields in tests behave like they do in normal Spring-Beans; they get injected with the actual beans configured in the application (xml, @Bean in a @Configuration, or @Component/@Service).

    @MockBean creates a mock that they behave like normal mocks that you can control with when/then etc and check with verify and suchlike. The thing that is special about them is that they get injected into other beans in the context (for instance when you call Mockito.initAnnotations(this)).