Question
This Content is from Stack Overflow. Question asked by mtnp
I have a class test which send me an error when I run the test.
I followed several threads and I have the right import “import org.junit.jupiter.api.Test”
So I don’t understand why it sends me this error :
Cannot invoke “org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)” because “this.mockMvc” is null
My code :
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(TestController.class)
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CreateMessageProvider createMessageProvider;
@Test
public void test() throws Exception {
this.mockMvc.perform(get("/test"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string("OK"));
}
}
Solution
Use these annotations :
@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
Answered by amine
This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 4.0.