Spring MVC 单元测试Demo

  

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:applicationContext.xml","classpath:webApplicationContext.xml"})
public class XXXXControllerTest{

    private Logger logger = LoggerFactory.getLogger(XXXXServiceTest.class);

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void startUp(){
        mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void mock_mainPageInfo_index() throws Exception {
        String requestUrl = "/index?userId={userId}";
        String[] midValue = new String[]{"369350"};
        MvcResult result = mockMvc.perform(get(requestUrl,midValue)).andReturn();
        ModelAndView modelAndView = result.getModelAndView();
        ModelMap modelMap = modelAndView.getModelMap();
        Assert.assertEquals("/mainPageInfo/index", modelAndView.getViewName());    }
}
原文地址:https://www.cnblogs.com/mengjianzhou/p/7676898.html