SpringMVC 单元测试

引入包:

import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

注入需要的组件:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {
        "classpath:spring/applicationContext.xml",
        "classpath:spring/spring-mvc-servlet.xml"
})
public class SpringMVCTest {

    @Autowired
    private WebApplicationContext wac;

    protected MockMvc mockMvc;

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

    @Test
    public void empty() {

    }

}

编写单元测试,这个例子是提交一个整体的字符串

@Test
public void testPostBody() throws Exception {

    String jsonString = JsonObjectUtils.beanToJson(ImmutableMap.of("username", "me", "password", "123456",
            "timestamp", System.currentTimeMillis()));
    
    ResultActions resultActions = mockMvc.perform(
            (post("/api/login.do")
                    .contentType(org.springframework.http.MediaType.APPLICATION_JSON)
                    .content(jsonString).characterEncoding("utf-8")))
            .andExpect(status().isOk()).andDo(print());
    String contentAsString = resultActions.andReturn().getResponse().getContentAsString();
    System.out.println(contentAsString);
}