I am trying to test Spring Boot's Rest controller.
Problem:
I am using @MockitoBean annotation for mocking the ContactService.java class. The Rest controller depends on this ContactService.java class.
Following the docs on setting up MockMvc, I have the following code:
public class ContactRestControllerTest {
private MockMvc mockMvc;
@MockitoBean
private ContactService contactService;
@BeforeEach
void setup() {
MockitoAnnotations.openMocks(this);
this.objectMapper = new ObjectMapper();
this.mockMvc = MockMvcBuilders
.standaloneSetup(new ContactRestController(contactService))
.build();
}
@Test
void getMessagesByStatus() throws Exception {
final String STATUS = "Open";
String messageListStr = "[ { ... } ]";
Page<List<ContactMessage>> pagedContactMessageList = // omitted for brevity...
Mockito.when(
this.contactService.getContactMessages(Mockito.eq(STATUS), Mockito.anyMap())
).thenReturn(pagedContactMessageList);
mockMvc.perform(...); // omitted for brevity
}
}
The above code throws the NullPointerException:
java.lang.NullPointerException: Cannot invoke "...ContactService.getContactMessages(String, java.util.Map)" because "this.contactService" is null
at ....ContactRestControllerTest.getMessagesByStatus(ContactRestControllerTest.java:151)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
Question:
Why is contactService null even through it is annotated with @MockitoBean and MockitoAnnotations.openMocks(this); is also called?
If I use the @WebMvcTest(ContactRestController.class) annotation over the test class, the test runs successfully. In this case, I don't even need to call MockitoAnnotations.openMocks(this). Everything just works fine.
If this is the correct way, then why do the docs on setting up MockMvc show a different way and what needs to be done to make that work? What am I missing here?
Spring boot version: 3.4.3
@WebMvcTestand Spring Boot testing in general adds additional support.