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方法

最新文章

  1. ubuntu下载工具uget和aria2
  2. Linux下,telnet命令如何退出
  3. Waiting Processed Cancelable ShowDialog (Release 2)
  4. BarEditItem ContentTemplate
  5. 2 CSS
  6. Nape的回调系统 nape.callbacks
  7. C#中Strings VS. StringBuilder
  8. Web---创建Servlet的3种方式、简单的用户注册功能
  9. Design Pattern ——Factory Method&amp;Abstract Factory
  10. Chrome真机调试步骤
  11. CSS3匹配屏幕横竖状态
  12. C part 1 -- 指令篇
  13. trove manual installation 翻译
  14. GUID的获取
  15. 安装配置rsync服务端
  16. InputStreamReader读取文件出现乱码
  17. 15_Python模块化编程_Python编程之路
  18. 对半导体制造(FAB)工种的全方位解析
  19. 停止node进程和查看react-native-cli
  20. VUE 组件通信总结

热门文章

  1. Python 操作MySQL 数据库
  2. Linux下OpenSSL加密解密压缩文件(AES加密压缩文件)
  3. java 爬虫:开源java爬虫 swing工具 Imgraber
  4. J.U.C之AQS:阻塞和唤醒线程
  5. kvm第五章--虚拟迁移
  6. PimaIndiansdiabetes-数据预处理实验(一)
  7. Linux提供哪些功能
  8. jquery基础知识2
  9. PHP搭建大文件切割分块上传功能示例
  10. 一次vaccum导致的事故