WebApplicationContext doesn't autowire
There is no WebApplicationContext
only an ApplicationContext
unless you add the @WebAppConfiguration
to your test class.
@ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class CandidateControllerTest { ... }
Instead of the @RunWith
annotation you can also extend one of springs convenience classes.
@ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" })
@WebAppConfiguration
public class CandidateControllerTest extends AbstractJUnit4SpringContextTests { ... }
Links
- WebAppConfiguration javadoc
- Reference Guide
I had the same issue using TestNG & Mockito.
Turns out wac isn't autowired and available in @BeforeTest methods but is in @Test methods.
I moved this
mockMvc = MockMvcBuilders.webApplicationContextSetup(wac).build();
to an @Test method and presto, it works!
Here's the link I found with the solution: http://forum.spring.io/forum/spring-projects/web/737624-problem-with-autowiring-webapplicationcontext-with-annotationconfigcontextloader
WebApplicationContext is required
and NullPointerException
are the most confusing errors I faced as beginner to TestNG and Spring Test Framework. These are happened due to simple mistakes like forget to `extends AbstractTestNGSpringContextTests1 etc. To avoid those errors I'll give you the code template 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 to test home page. If you are Beginner, an error occur such as I mentioned above, first check whether extends AbstractTestNGSpringContextTests
and this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
are in the proper places.
Another thing is you can use @BeforeMethod annotation to stop repeating this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
in each module. You should have add @BeforeMethod
like Below.
@BeforeMethod
public void setWac(){
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}