白羽
2018-06-04
来源 :网络
阅读 1780
评论 0
摘要:单元测试是检测代码严密性的最好方式,不仅能减少和预防bug的产生,还能自己二次检查代码或者考虑review必要,如果你还没有养成这个习惯,可要开始关注了。 本文主要讲述单元测试使用以及多环境配置,
本节主要讲述单元测试使用以及多环境配置
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));
}
}本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标软件测试之测试技术频道!
喜欢 | 0
不喜欢 | 0
您输入的评论内容中包含违禁敏感词
我知道了

请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式AI+学习就业服务平台 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号