Springboot单元测试实战篇

发表于:2018-1-11 11:13

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:刘志鹏    来源:51Testing软件测试网采编

  单元测试是检测代码严密性的最好方式,不仅能减少和预防bug的产生,还能自己二次检查代码或者考虑review必要,如果你还没有养成这个习惯,可要开始关注了。
  上节以 springboot快速实战搭建篇 快速入门,本节主要讲述单元测试使用以及多环境配置
  maven依赖
  在pom.xml中引入
  <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
  </dependency>
  项目属性文件配置
  application.properties配置文件内容如下:
  msg=Hello
  1.基础使用,示例以两种方式读取项目属性文件的值
  加入@SpringBootTest注解和@RunWith(SpringRunner.class)注解。
  注:1.4.0版本之后这样使用即可
  import org.junit.Test;
  import org.junit.runner.RunWith;
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.beans.factory.annotation.Value;
  import org.springframework.boot.test.context.SpringBootTest;
  import org.springframework.core.env.Environment;
  import org.springframework.test.context.junit4.SpringRunner;
  @SpringBootTest
  @RunWith(SpringRunner.class)
  public class Test {
  @Value("${msg}")
  private String msg;
  @Autowired
  private Environment env;
  @Test
  public void test() {
  System.out.println(msg);
  }
  @Test
  public void test1() {
  System.out.println(env.getProperty("msg"));
  }
  }
  @RunWith(SpringJUnit4ClassRunner.class),这是JUnit的注解,通过这个注解让SpringJUnit4ClassRunner这个类提供Spring测试上下文。
  2.使用web模块的单元测试,模拟执行controller等功能
  我们以一个简单的Testcontroller为例,get请求访问 路径+"/hello"返回hello字符串。我们想要验证接口是否正常以及返回预期结果判定,则编写以下测试示例
  @RunWith(SpringRunner.class)
  @SpringBootTest
  public class SpringbootDemoApplicationTests {
  private MockMvc mvc;
  @Before
  public  void setUp() throws Exception {
  //初始化
  mvc = MockMvcBuilders.standaloneSetup(new TestController()).build();
  }
  @Test
  public  void hello() throws Exception {
  String url = "/hello";//访问url
  String expectedResult = "hello";//预期返回结果
  MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(url).accept(MediaType.APPLICATION_JSON))
  .andReturn();
  //访问返回状态
  int status = mvcResult.getResponse().getStatus();
  //接口返回结果
  String content = mvcResult.getResponse().getContentAsString();
  //打印结果和状态
  //System.out.println(status);
  //System.out.println(content);
  //断言预期结果和状态
  Assert.assertTrue("错误", status == 200);
  Assert.assertFalse("错误", status != 200);
  Assert.assertTrue("数据一致", expectedResult.equals(content));
  Assert.assertFalse("数据不一致", !expectedResult.equals(content));
  }
  }

上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。
精选软件测试好文,快来阅读吧~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号