分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

使用MockMVC与Junit进行单体测试

发布时间:2023-09-06 01:12责任编辑:林大明关键词:MVC

1、pom.xml追加

junit

spring-test

2、测试共通类

@ContextConfiguration(locations = { "classpath:springframework/application-context.xml", ???????"classpath:springframework/dispatcherservlet-servlet.xml" })@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@Transactionalabstract 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进行单体测试

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved