Issue
I have this MvcTest in my application:
@SpringBootTest
@WebMvcTest
public class BarsControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
but when I run the test mockMvc is null when running the tests.
Solution
You shouldn't use @WebMvcTest
and @SpringBootTest
together.
If you want to test both web layer and other layers Use @AutoConfigureMockMvc
and @SpringBootTest
together:
@SpringBootTest
@AutoConfigureMockMvc
public class BarsControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
Or if you only want to test web layer you can use just @WebMvcTest
: note the this does not load full spring application context(It only loads web layer)
@WebMvcTest
public class BarsControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testBars() throws Exception {
mockMvc.perform(get("/bars")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$.*", hasSize(1)));
}
}
Answered By - Tashkhisi
Answer Checked By - Marie Seifert (JavaFixing Admin)