WebApplicationContext is required and NullPointerException are the most confusing errors that I encountered as new to TestNG and Spring Test Framework. This is due to simple errors, such as βforgettingβ about the AbstractTestNGSpringContextTests1 extension, etc. To avoid these errors, I will give you the code template that I use.
@Test @WebAppConfiguration @ContextConfiguration(classes = WebConfig.class) //You can use your xml too public class YourControllerTest extends AbstractTestNGSpringContextTests { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Test public void getEmailVerificationTest() throws Exception { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); this.mockMvc.perform(get("/home") .accept(MediaType.ALL)) .andExpect(status().isOk()) .andExpect(view().name("home/index")); } }
This is sample code for checking the home page. If you are new, an error occurs, for example, mentioned above, first check if extends AbstractTestNGSpringContextTests and this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); in appropriate places.
Another thing, you can use the @BeforeMethod annotation to stop repeating this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); in each module. You should add @BeforeMethod as shown below.
@BeforeMethod public void setWac(){ this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); }
source share