码迷,mamicode.com
首页 > Web开发 > 详细

使用MockMVC与Junit进行单体测试

时间:2017-09-17 20:56:20      阅读:354      评论:0      收藏:0      [点我收藏+]

标签:add   extends   div   tran   mapper   isp   logs   build   nsa   

1、pom.xml追加

junit

spring-test

 

2、测试共通类

@ContextConfiguration(locations = { "classpath:springframework/application-context.xml",
        "classpath:springframework/dispatcherservlet-servlet.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@Transactional
abstract public class TestCommon {

    private static final Logger LOG = LogManager.getLogger();

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

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

}

 

3、示例

public class MemberTest extends TestCommon {

    /**
     * 请求:新增,请求方式:POST
     */
    @Test
    @Rollback(false)
    public void add() throws Exception {
        String uri = "/member/add";
        Map<String, String> contentParams = new HashMap<>();
        contentParams.put("name", "测试用姓名");
        contentParams.put("sex", "男");
        String jsonStr = new ObjectMapper().writeValueAsString(contentParams);
        MockHttpServletResponse response = mockMvc.perform(
                MockMvcRequestBuilders.post(uri).contentType(MediaType.APPLICATION_JSON_UTF8).content(jsonStr))
                .andReturn().getResponse();
        if (response.getStatus() != HttpServletResponse.SC_OK) {
            fail("Http" + response.getStatus());
        }
            LOG.info(response.getContentAsString());
    }

}

 

4、如果想测试除post以外的请求,可以调用MockMvcRequestBuilders的get, put等方法

 

5、类似于URL中的“?page=2”的参数,可以调用MockMvcRequestBuilders的params方法

 

使用MockMVC与Junit进行单体测试

标签:add   extends   div   tran   mapper   isp   logs   build   nsa   

原文地址:http://www.cnblogs.com/deolin/p/7536858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!