简体   繁体   中英

Spring MVC testing with MockMvc - webapplicationcontext is null

I am trying to create JUnit test cases for Spring MVC controllers using junit & spring-test api. Since I have lot of beandefinitions in my app, I used LazyInitDefaultBeanDefinitionDocumentReader and have written a CustomContextLoader .

My sample test class would be:

    @RunWith(SpringJUnit4ClassRunner.class)  
    @ContextConfiguration(loader=com.xyz.CustomXmlContextLoader.class,
    locations={"file:///D:/web-module/src/test/resources/conf/application-config-controller-test.xml"})
    @WebAppConfiguration
    public class LoginControllerTest {


        @Autowired  
        private WebApplicationContext wac;

        private MockMvc mockMvc;  

        @Test  
        public void testShowForm_forgetUserID() throws Exception {  

        System.out.println("webappcontext::"+wac);
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  

        mockMvc.perform(get("/login.form")).andExpect(status().isOk());

        }  
}

Here, if I execute the above code, wac is not autowired and it returns null. But if I remove loader=com.xyz.CustomContextLoader from @ContextConfiguration , it works fine.

I need to have both lazy load and MockMvc for testing. Am I missing anything? Is there any better solution?

Another solution might be that you use "@ContextConfiguration"-Annotation in your test class

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { CustomDataTestConfig.class })
@WebMvcTest(ClientDataEndpoint.class)
public class ClientDataEndpointMvcTest
  • Create a "@Configuration" file with the code

(CustomDataTestConfig.java):

@Configuration 
public class CustomDataTestConfig
{
    @Bean
    public LoginControllerEndpoint LoginControllerEndpoint()
    {
          return Mockito.mock(LoginControllerEndpoint.class);
    }
}

My example for a Mvc Test:

RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { ClientDataTestConfig.class })
@WebMvcTest(ClientDataEndpoint.class)
public class ClientDataEndpointMvcTest
{

  @MockBean
  private ClientDataEndpoint clientDataEndpoint;

  @Autowired
  private MockMvc mockMvc;

  // MockitoJUnitRunner
  @InjectMocks
  private ClientDataEndpoint sut;

  @Autowired
  private WebApplicationContext wac;

  @Autowired
  MockHttpSession session;

  @Autowired
  MockHttpServletRequest request;

  @Before
  public void beforeTest()
  {
    // Mocking the Web Context Beans
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
        when(clientDataEndpoint.getBirol()).thenCallRealMethod();
  }
  @Test
  public void testClientdata() throws Exception
  {
    ServletContext servletContext = wac.getServletContext();
    Assert.assertNotNull(servletContext);
    // simple jUnitTest
     Assert.assertEquals("birol", this.clientDataEndpoint.getBirol());


    // Testing Rest API Endpoint
     MvcResult result = this.mockMvc.perform(get("/clientdata/birol").accept("application/json")).andExpect(status().isOk()).andReturn();
  }
  • the "when(clientDataEndpoint.getBirol()).thenCallRealMethod();" in the @Before is a fallback, to call a real method of a Mocked object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM