博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMvc单元测试
阅读量:4230 次
发布时间:2019-05-26

本文共 1503 字,大约阅读时间需要 5 分钟。

现在越来越多的现实开发中,我们是先有需求,然后根据我们想要的样子去开发。

这里引入一个概念交测试驱动开发,我们按照需求先写一个自己预期结果的测试用例,不然不断的编码和重构,最终让测试用例通过测试,

这样才能保证软件的质量和可控性。

直接看例子,注解都已经写的比较详细了。

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = {MyMvcConfig.class})@WebAppConfiguration("src/main/resources")//声明加载的ApplicationContext是一个WebApplicationContext。public class TestControllerIntegrationTests {    private MockMvc mockMvc;//模拟mvc对象    @Autowired    private DemoService demoService;    @Autowired    WebApplicationContext wac;//可注入WebApplicationContext    @Autowired    MockHttpSession session;//可注入模拟的http session    @Autowired    MockHttpServletRequest request;    @Before    public void setup(){
//初始化工作 this.mockMvc= MockMvcBuilders.webAppContextSetup(this.wac).build(); } @Test public void testNormalController() throws Exception{ mockMvc.perform(get("/normal"))//模拟向/normal进行get请求 .andExpect(status().isOk())//预期控制返回状态为200 .andExpect(view().name("page"))//预期控制返回状态为200 .andExpect(forwardedUrl("/WEB-INF/classes/views/page.jsp"))//预期页面转向的真正路径 .andExpect(model().attribute("msg",demoService.saySomething()));//预期model中的值 } @Test public void testRestController() throws Exception{ mockMvc.perform(get("/testRest")) .andExpect(status().isOk()) .andExpect(content().contentType("text/plain;charset=UTF-8"))//预期返回类型 .andExpect(content().string(demoService.saySomething()));//预期返回值的内容 }}

转载地址:http://rljqi.baihongyu.com/

你可能感兴趣的文章
加密与解密、抓包扫描
查看>>
16.一级目录、历史命令,du,date,zip,快捷方式
查看>>
MySQL的基本管理
查看>>
MySQL 表结构与键值
查看>>
MySQL存储引擎,表记录管理
查看>>
Mysql多表查询语句,授权用户与密码更改
查看>>
MySQL 备份与恢复
查看>>
采用IC传感器的相对湿度测量
查看>>
皮带传动实验
查看>>
微软的人才观
查看>>
Blizzard的MPQ文件格式搜索算法
查看>>
你的变量究竟存储在什么地方?
查看>>
s3c2410 中断异常处理(转)
查看>>
对张孝祥C语言试题其中一题的探讨 (转载)
查看>>
一些好的网站
查看>>
WinCE中的虚拟地址和实际的物理地址是如何对应
查看>>
Microsoft Windows CE 的内存使用
查看>>
makefile入门
查看>>
中科院计算所Goddon CPU诞生历史!牛!
查看>>
ispPAC
查看>>