Spring Junit4 单元测试
来源:互联网 发布:于建国 人工智能 编辑:程序博客网 时间:2024/05/18 01:06
Spring
@RunWith(SpringJUnit4ClassRunner.class)//基于Junit4的Spring测试框架 @ContextConfiguration(location={"/applicationContext.xml"})//启动Spring容器 public class TestUserService{ //注入Spring容器中的bean @AutoWired private UserService userService; @Test public void hasMatchUser(){ boolean result = userService.hasMatchUser("admin","123456"); Assert.assertTrue("错误,结果非预期", result); } }
Spring MVC
测试Controller层 Get方法
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath*:/applicationContext.xml","classpath*:/spring-mvc.xml"}) public class TestController { private MockMvc mockMvc; @Autowired WebApplicationContext webApplicationContext; @Before public void setUp(){ mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void testLogin() { String url = "/citys/1"; MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url) .accept(MediaType.APPLICATION_JSON)) .andReturn(); int status = mvcResult.getResponse().getStatus(); String data = mvcResult.getResponse().getContentAsString(); logger.info("返回的数据: {}", data); // jackson 转化使用 ObjectMapper mapper = new ObjectMapper(); City city = mapper.readValue(data, City.class); String dataStr = mapper.writeValueAsString(city); // fastjson 转化使用 City cityObj = JSON.parseObject(data, City.class); String cityStr = JSON.toJSONString(cityObj); logger.info("jackson转化后的数据: {}", dataStr); logger.info("fastjson转化后的数据: {}", cityStr); assertTrue("错误,正确返回值应该为200", status == 200); assertTrue("错误,正确应该是1", city.getId() == 1); } }
测试Controller层 Post方法
param传参
@Test public void delBanner() throws Exception { String url = "/delBanner"; MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.post(url) .param("id", "26") .accept(MediaType.APPLICATION_JSON) ).andExpect(MockMvcResultMatchers.status().isOk()) .andReturn(); int status = mvcResult.getResponse().getStatus(); String data = mvcResult.getResponse().getContentAsString(); logger.info("返回的数据: {}", data); System.out.println(data);// assertTrue("错误,正确返回值应该为200", status == 200); }
contentType 传参
@Test public void modifyBanner() throws Exception { String url = "/modifyBanner"; ScwCommunityBanner scwCommunityBanner = new ScwCommunityBanner(); scwCommunityBanner.setId(26); scwCommunityBanner.setExpTimeStr(""); scwCommunityBanner.setStartTimeStr("2017-05-10 11:20:10"); scwCommunityBanner.setTitle("单元测试"); scwCommunityBanner.setImgUrl("http://img.qq.com/images/thumb/thumbnail_484.jpg"); scwCommunityBanner.setLinkUrl("https://www.baidu.com"); scwCommunityBanner.setBannerType((byte)2); String requestJson = JSONObject.toJSONString(scwCommunityBanner); MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.post(url) .contentType(MediaType.APPLICATION_JSON) .content(requestJson.getBytes()) .accept(MediaType.APPLICATION_JSON) ).andExpect(MockMvcResultMatchers.status().isOk()) .andReturn();// int status = mvcResult.getResponse().getStatus(); String data = mvcResult.getResponse().getContentAsString(); logger.info("返回的数据: {}", data); System.out.println(data); // fastjson 转化使用 CommonResult result = JSON.parseObject(data, CommonResult.class); assertTrue("错误,正确返回值应该为1", result.getStatus() == 1); }
Spring Boot
测试Controller层
@RunWith(SpringRunner.class)@SpringBootTestpublic class CityControllerTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private MockMvc mockMvc; @Autowired WebApplicationContext webApplicationContext; @Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void findCityById() throws Exception { String url = "/citys/1"; MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url) .accept(MediaType.APPLICATION_JSON)) .andReturn(); int status = mvcResult.getResponse().getStatus(); String data = mvcResult.getResponse().getContentAsString(); logger.info("返回的数据: {}", data); // jackson 转化使用 ObjectMapper mapper = new ObjectMapper(); City city = mapper.readValue(data, City.class); String dataStr = mapper.writeValueAsString(city); // fastjson 转化使用 City cityObj = JSON.parseObject(data, City.class); String cityStr = JSON.toJSONString(cityObj); logger.info("jackson转化后的数据: {}", dataStr); logger.info("fastjson转化后的数据: {}", cityStr); assertTrue("错误,正确返回值应该为200", status == 200); assertTrue("错误,正确应该是1", city.getId() == 1); }}
更优雅的测试Controller层
package com.jeiker.demo;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;import org.springframework.test.context.junit4.SpringRunner;import org.springframework.test.web.servlet.MockMvc;import static org.hamcrest.Matchers.containsString;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document;import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;// 提供Spring测试上下文@RunWith(SpringRunner.class)@WebMvcTest(HomeController.class)@AutoConfigureRestDocs(outputDir = "target/snippets")public class HomeControllerTest { @Autowired private MockMvc mockMvc; @Test public void hello() throws Exception { // 建立web请求 this.mockMvc.perform(get("/")) // 打印结果 .andDo(print()) // 检查状态码为200 .andExpect(status().isOk()) // 检查内容有"Hello World" .andExpect(content().string(containsString("Hello World"))) // 检查在根目录下有一个名为name的节点,并且该节点对应的值是“Hello World” .andExpect(jsonPath("$.message").value("Hello World")) // 生成文件目录名称:home .andDo(document("home")); }}
测试Dao层
@RunWith(SpringRunner.class)@SpringBootTestpublic class CityMapperTest { @Autowired CityMapper cityMapper; @Test public void selectByPrimaryKey() throws Exception { City city = cityMapper.selectByPrimaryKey(1); assertTrue("错误:返回结果应该为1.", city.getId() == 1); }}
0 0
- junit4 spring 便捷单元测试
- Spring集成Junit4单元测试
- Spring集成Junit4单元测试
- Spring Junit4 单元测试
- Spring+junit4单元测试原理解析
- Spring MVC Junit4 单元测试 JunitTest
- Spring AOP实例 Junit4单元测试
- Spring整合Junit4进行单元测试
- java-junit4+spring 集成单元测试
- Spring Junit4 单元测试回滚
- Spring整合Junit4进行单元测试
- JUnit4结合spring做单元测试
- Spring 整合Junit4进行单元测试
- Spring整合Junit4进行单元测试
- spring整合Junit4进行单元测试
- Junit4+Spring单元测试写到类上面的注解
- 浅谈Spring测试框架+junit4单元测试原理
- spring项目中使用单元测试JUnit4
- Java中的反射机制(2)
- GYM 101147 C.The Wall(二分匹配-hungary)
- [SLAM]Karto SLAM算法学习
- 《ACM程序设计》书中题目-专题总结
- 基于深度学习框架theano的库-----Lasagne
- Spring Junit4 单元测试
- Ubuntu14.04 安装jdk
- POJ 1664 放苹果
- 抽象工厂模式
- 关于自动装箱和拆箱
- Fedora 64位 android "failed to create the SD card" 解决方法
- Accelerated C++<3-2>
- 如何把vim打造成IDE
- 用python完成一个爬虫,实现从豆瓣“西安单身小组”上抓取若干征男友帖子