使用MockMvc进行Spring MVC测试 - webapplicationcontext为null

时间:2014-06-05 10:40:19

标签: spring spring-mvc junit mockmvc

我正在尝试使用junit& amp;创建Spring MVC控制器的JUnit测试用例。弹簧测试api。由于我的应用程序中有很多beandefinitions,因此我使用LazyInitDefaultBeanDefinitionDocumentReader编写了CustomContextLoader

我的示例测试类将是:

    @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());

        }  
}

这里,如果我执行上面的代码,wac没有自动装配,它返回null。但是,如果我从loader=com.xyz.CustomContextLoader中移除@ContextConfiguration,则可以正常使用。

我需要同时使用延迟加载和MockMvc进行测试。我错过了什么吗?有没有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

另一种解决方案可能是在测试类中使用“ @ContextConfiguration”-注释

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { CustomDataTestConfig.class })
@WebMvcTest(ClientDataEndpoint.class)
public class ClientDataEndpointMvcTest
  • 使用代码创建“ @Configuration”文件

(CustomDataTestConfig.java):

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

我的Mvc测试示例:

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();
  }
  • “何时(clientDataEndpoint.getBirol())。thenCallRealMethod();” @Before中的一个后备选项,以调用模拟对象的真实方法