SpringMVC 单元测试

0
(0)

引入包:

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);
}

这篇文章有用吗?

平均评分 0 / 5. 投票数: 0

到目前为止还没有投票!成为第一位评论此文章。

很抱歉,这篇文章对您没有用!

让我们改善这篇文章!

告诉我们我们如何改善这篇文章?

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据