Befolgen -Java PrettyPrint-Override ">
Code: Select all
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 pagedContactMessageList = // omitted for brevity...
Mockito.when(
this.contactService.getContactMessages(Mockito.eq(STATUS), Mockito.anyMap())
).thenReturn(pagedContactMessageList);
mockMvc.perform(...); // omitted for brevity
}
}
< /code>
Der obige Code löst die NullPointerexception aus: < /p>
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)
Warum wird ContactService null sogar mit @mockitobean und mockitoannotations.openmocks (diese ); wird auch genannt?
Wenn ich die verwende @Webmvctest (contactrestController.class) Annotation gegenüber der Testklasse, der Test wird erfolgreich ausgeführt. In diesem Fall muss ich nicht einmal Mockitoannotations anrufen. OpenMocks (this) . Alles funktioniert einfach einwandfrei. Was fehlt mir hier?>