I expected @MockitoBean to also be injected into the Spring Context as @MockBean did.

Minimal reproducible project: https://github.com/Sax388/mockito-bean-failing-when-mock-bean-does-not

When using

@MockitoBean private TokenService tokenService;

in https://github.com/Sax388/mockito-bean-failing-when-mock-bean-does-not/blob/c75c41eecb69080ea66292c07930b419de03a253/src/test/java/com/example/demo/cucumber/steps/RequestHelper.java#L24 then the test fails with

Cannot invoke "com.example.demo.TokenService.getTenantName()" because "this.tokenService" is null
java.lang.NullPointerException: Cannot invoke "com.example.demo.TokenService.getTenantName()" because "this.tokenService" is null
    at com.example.demo.cucumber.steps.RequestHelper.adminRequest(RequestHelper.java:27)
    at com.example.demo.cucumber.steps.TestSteps.makeTestRequest(TestSteps.java:16)
    at ✽.I make a test request(classpath:features/test.feature:4)

When using

@MockBean private TokenService tokenService;

the test passes.

Comment From: sbrannen

Hi @Sax388,

Congratulations on submitting your first issue for the Spring Framework! 👍

The behavior you have encountered is expected.

As stated in the Javadoc for @MockitoBean (bold emphasis added):

@MockitoBean is an annotation that can be used in test classes to override beans in a test's ApplicationContext using Mockito mocks.

Consequently, @MockitoBean is not supported on fields in a @Component class like in your example.

Regards,

Sam

Comment From: sbrannen

I'm not familiar with using Cucumber with Spring's testing support, but I imagine the following would be one option to get your example working.

Annotate CucumberBootstrap with @MockitoBean.

@CucumberContextConfiguration
@SpringBootTest(
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
    properties = {"spring.main.allow-bean-definition-overriding=true"})
@ContextConfiguration(classes = DemoApplication.class)
@MockitoBean(types = TokenService.class)
public class CucumberBootstrap {}

In RequestHelper, replace:

@MockitoBean private TokenService tokenService;

with:

@Autowired private TokenService tokenService;

Hope that helps!

Comment From: Sax388

@sbrannen That was exactly what I was looking for! Perfect, thanks a million for the quick evaluation and support.

Comment From: sbrannen

That was exactly what I was looking for!

Awesome! Really glad to hear that that works for you. 😎

Perfect, thanks a million for the quick evaluation and support.

You're very welcome, and thanks for providing the feedback.