SpringMVC 单元测试

2021-12-08 08:56:33 浏览数 (1)

引入包:

代码语言:javascript复制
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.*;

注入需要的组件:

代码语言:javascript复制
@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() {

    }

}

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

代码语言:javascript复制
@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);
}

0 人点赞