1.为什么要写测试用例

1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率 
2. 可以自动测试,可以在项目打包前进行测试校验 
3. 可以及时发现因为修改代码导致新的问题的出现,并及时解决

2.Junit基本注解介绍

//在所有测试方法前执行一次,一般在其中写上整体初始化的代码 
@BeforeClass

//在所有测试方法后执行一次,一般在其中写上销毁和释放资源的代码 
@AfterClass

//在每个测试方法前执行,一般用来初始化方法(比如我们在测试别的方法时,类中与其他测试方法共享的值已经被改变,为了保证测试结果的有效性,我们会在@Before注解的方法中重置数据) 
@Before

//在每个测试方法后执行,在方法执行完成后要做的事情 
@After

// 测试方法执行超过1000毫秒后算超时,测试将失败 
@Test(timeout = 1000)

// 测试方法期望得到的异常类,如果方法执行没有抛出指定的异常,则测试失败 
@Test(expected = Exception.class)

// 执行测试时将忽略掉此方法,如果用于修饰类,则忽略整个类 
@Ignore(“not ready yet”) 
@Test

@RunWith 
在JUnit中有很多个Runner,他们负责调用你的测试代码,每一个Runner都有各自的特殊功能,你要根据需要选择不同的Runner来运行你的测试代码。 
如果我们只是简单的做普通Java测试,不涉及Spring Web项目,你可以省略@RunWith注解,这样系统会自动使用默认Runner来运行你的代码。

3.单元测试

1、在pom包中添加spring-boot-starter-test包引用

  spring-boot-starter-test :测试模块,包括JUnit、Hamcrest、Mockito

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

2、开发测试类

  以最简单的helloworld为例,在测试类的类头部需要添加:@RunWith(SpringRunner.class)@SpringBootTest注解,在测试方法的顶端添加@Test即可,最后在方法上点击右键run就可以运行。

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests { @Test
public void hello() {
System.out.println("hello world");
} }

  实际使用中,可以按照项目的正常使用去注入dao层代码或者是service层代码进行测试验证,spring-boot-starter-test提供很多基础用法,更难得的是增加了对Controller层测试的支持。

//简单验证结果集是否正确
Assert.assertEquals(3, userMapper.getAll().size()); //验证结果集,提示
Assert.assertTrue("错误,正确的返回值为200", status == 200);
Assert.assertFalse("错误,正确的返回值为200", status != 200);

  引入了MockMvc支持了对Controller层的测试,简单示例如下:

public class HelloControlerTests {

    private MockMvc mvc;

    //初始化执行
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
} //验证controller是否正常响应并打印返回结果
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
} //验证controller是否正常响应并判断返回结果是否正确
@Test
public void testHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World")));
} }

4.SpringBoot Web项目中中如何使用Junit

@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class) // 指定我们SpringBoot工程的Application启动类
@WebAppConfiguration // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。

测试方法使用@Test注解标注即可

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
@WebAppConfiguration
public class StudentTest { @Autowired
private StudentService studentService; @Test
public void likeName() {
assertArrayEquals(
new Object[]{
studentService.likeName("小明2").size() > 0,
studentService.likeName("坏").size() > 0,
studentService.likeName("莉莉").size() > 0
},
new Object[]{
true,
false,
true
}
);
// assertTrue(studentService.likeName("小明2").size() > 0);
} }

  https://www.cnblogs.com/cx987514451/p/9304525.html

  https://www.cnblogs.com/shunyang/p/8681111.html

  https://www.cnblogs.com/aston/p/7259825.html

5.使用Junit测试HTTP的API接口

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
//@WebAppConfiguration // 使用@WebIntegrationTest注解需要将@WebAppConfiguration注释掉
@WebIntegrationTest("server.port:0")// 使用0表示端口号随机,也可以具体指定如8888这样的固定端口
public class HelloControllerTest { private String dateReg;
private Pattern pattern;
private RestTemplate template = new TestRestTemplate();
@Value("${local.server.port}")// 注入端口号
private int port; @Test
public void test3(){
String url = "http://localhost:"+port+"/myspringboot/hello/info";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("name", "Tom");
map.add("name1", "Lily");
String result = template.postForObject(url, map, String.class);
System.out.println(result);
assertNotNull(result);
assertThat(result, Matchers.containsString("Tom"));
} }

6.捕获输出

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
//@WebAppConfiguration // 使用@WebIntegrationTest注解需要将@WebAppConfiguration注释掉
@WebIntegrationTest("server.port:0")// 使用0表示端口号随机,也可以具体指定如8888这样的固定端口
public class HelloControllerTest { @Value("${local.server.port}")// 注入端口号
private int port; private static final Logger logger = LoggerFactory.getLogger(StudentController.class); @Rule
// 这里注意,使用@Rule注解必须要用public
public OutputCapture capture = new OutputCapture(); @Test
public void test4(){
System.out.println("HelloWorld");
logger.info("logo日志也会被capture捕获测试输出");
assertThat(capture.toString(), Matchers.containsString("World"));
}
}

7.打包测试

  打包测试,就是新增一个类,然后将我们写好的其他测试类配置在一起,然后直接运行这个类就达到同时运行其他几个测试的目的。

@RunWith(Suite.class)
@SuiteClasses({ATest.class, BTest.class, CTest.class})
public class ABCSuite {
// 类中不需要编写代码
}

参考:

   http://www.ityouknow.com/springboot/2017/05/09/springboot-deploy.html

   https://blog.csdn.net/catoop/article/details/50752964

五、springboot单元测试的更多相关文章

  1. Springboot单元测试Junit深度实践

    Springboot单元测试Junit深度实践 前言 单元测试的好处估计大家也都知道了,但是大家可以发现在国内IT公司中真正推行单测的很少很少,一些大厂大部分也只是在核心产品推广单测来保障质量,今天这 ...

  2. springmvc,springboot单元测试配置

    1. springmvc单元测试配置 <dependency> <groupId>junit</groupId> <artifactId>junit&l ...

  3. springboot系列三、springboot 单元测试、配置访问路径、多个配置文件和多环境配置,项目打包发布

    一.单元测试 生成的demo里面包含spring-boot-starter-test :测试模块,包括JUnit.Hamcrest.Mockito,没有的手动加上. <dependency> ...

  4. SpringBoot单元测试中的事务和Session

    1.Springboot中使用junit编写单元测试,并且测试结果不影响数据库. 2.

  5. SpringBoot单元测试

    一.Service层Junit单元测试 需要的jar包 <dependency> <groupId>org.springframework.boot</groupId&g ...

  6. springboot(十二):springboot单元测试、打包部署

    单元测试 1.在pom包中添加spring-boot-starter-test包引用 <dependency> <groupId>org.springframework.boo ...

  7. Springboot单元测试(MockBean||SpyBean)

    转载:https://blog.csdn.net/maiyikai/article/details/78483423 本来要写springboot集成netty实现的,但是想起来单元测试没总结,那就趁 ...

  8. springBoot单元测试-基础单元测试

    1)在pom文件中加入junit支持 <!-- spring-boot-starter-test 单元测试 --> <dependency> <groupId>or ...

  9. 【使用篇二】SpringBoot单元测试(10)

    SpringCloud单元测试:https://www.cnblogs.com/myitnews/p/11796321.html 1. 创建项目Maven Project,修改pom.xml < ...

随机推荐

  1. yum报错Segmentation fault

    yum install 安装一个包,提示 Segmentation fault,可以确定的是这个源肯定是可用的. 经查询,是 libz 这个库存在多个版本,导致冲突. # ldconfig -v | ...

  2. bzoj 1539: [POI2005]Dwu-Double-row

    假设一列交换表示为1,不换表示为0. 身高相同的两个人相当于给其中两列了一个限制条件,要么是两个必须相等,要么一个为零一个为一. 有了关系后我们就可以把每列当成一个点建边,边权为0表示必须相同,1为必 ...

  3. centos7添加虚拟IP

    1.在网络配置文件中添加虚拟IP,vi /etc/sysconfig/network-scripts/ifcfg-eno16777736 TYPE="Ethernet" BOOTP ...

  4. 《剑指offer》— JavaScript(24)二叉树中和为某一值的路径

    二叉树中和为某一值的路径 题目描述 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径. 思路 前序遍历二叉树, ...

  5. centos 安装MATLAB :设置回环设备失败: 没有那个文件或目录

    基本参数:centos 7 x86_64,linux 系统, 安装matlab, 已经下载R2016b_glnxa64.iso 但挂载的时候遇到问题: [root@lf mnt]# mount -o  ...

  6. Git3:Git分支

    目录 一.概念 二.创建与合并分支 1.创建分支原理分析 2.创建分支语法 三.解决冲突 四.分支管理策略 1.保留分支历史 2.分支管理原则 五. bug分支 六.推送和拉取远程分支 一.概念 分支 ...

  7. CIDR 无类别域间路由

    参考百度百科 1.全称 CIDR的全称是Classless Inter-Domain Routing 2.作用 CIDR将路由集中起来,使一个IP地址代表主要骨干提供商服务的几千个IP地址,从而减轻I ...

  8. jquery如何获取input(file)控件上传的图片名称,即"11111.jpg"

    html代码:<input name=file" type="file" id="file"/> Jquery代码:var file;$( ...

  9. 使用JavaScript 修改浏览器 URL 地址栏

    现在的浏览器里,有一个十分有趣的功能,你可以在不刷新页面的情况下修改浏览器URL;在浏览过程中.你可以将浏览历史储存起来,当你在浏览器点击后退按钮的时候,你可以冲浏览历史上获得回退的信息,这听起来并不 ...

  10. web打印难题—背景不打印的简单不完美解决方案

    web打印在一些开发中是比较常见的需求,最简单的办法是使用css print进行控制:对于一些建议可以参考http://slodive.com/web-development/css-print-pa ...