Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性。
凭本人的感觉和经验来说,在项目中完全按标准都写Junit用例覆盖大部分业务代码的,应该不会超过一半。

刚好前段时间写了一些关于SpringBoot的帖子,正好现在把Junit再拿出来从几个方面再说一下,也算是给一些新手参考了。

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

那么本文从以下几点来说明怎么使用Junit,Junit4比3要方便很多,细节大家可以自己了解下,主要就是版本4中对方法命名格式不再有要求,不再需要继承TestCase,一切都基于注解实现。

1、SpringBoot Web项目中中如何使用Junit

创建一个普通的Java类,在Junit4中不再需要继承TestCase类了。
因为我们是Web项目,所以在创建的Java类中添加注解:

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

接下来就可以编写测试方法了,测试方法使用@Test注解标注即可。
在该类中我们可以像平常开发一样,直接@Autowired来注入我们要测试的类实例。
下面是完整代码:

package org.springboot.sample;

import static org.junit.Assert.assertArrayEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springboot.sample.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration; /**
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年2月23日
*/
@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);
} }

接下来,你需要新增无数个测试类,编写无数个测试方法来保障我们开发完的程序的有效性。

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、参数化测试

Junit为我们提供的参数化测试需要使用 @RunWith(Parameterized.class)
然而因为Junit 使用@RunWith指定一个Runner,在我们更多情况下需要使用@RunWith(SpringJUnit4ClassRunner.class)来测试我们的Spring工程方法,所以我们使用assertArrayEquals 来对方法进行多种可能性测试便可。

下面是关于参数化测试的一个简单例子:

package org.springboot.sample;

import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.Collection; import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class)
public class ParameterTest { private String name;
private boolean result; /**
* 该构造方法的参数与下面@Parameters注解的方法中的Object数组中值的顺序对应
* @param name
* @param result
*/
public ParameterTest(String name, boolean result) {
super();
this.name = name;
this.result = result;
} @Test
public void test() {
assertTrue(name.contains("小") == result);
} /**
* 该方法返回Collection
*
* @return
* @author SHANHY
* @create 2016年2月26日
*/
@Parameters
public static Collection<?> data(){
// Object 数组中值的顺序注意要和上面的构造方法ParameterTest的参数对应
return Arrays.asList(new Object[][]{
{"小明2", true},
{"坏", false},
{"莉莉", false},
});
}
}

4、打包测试
正常情况下我们写了5个测试类,我们需要一个一个执行。
打包测试,就是新增一个类,然后将我们写好的其他测试类配置在一起,然后直接运行这个类就达到同时运行其他几个测试的目的。

代码如下:

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

5、使用Junit测试HTTP的API接口
我们可以直接使用这个来测试我们的Rest API,如果内部单元测试要求不是很严格,我们保证对外的API进行完全测试即可,因为API会调用内部的很多方法,姑且把它当做是整合测试吧。

下面是一个简单的例子:

package org.springboot.sample;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue; import java.util.regex.Matcher;
import java.util.regex.Pattern; import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate; /**
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年2月23日
*/
@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、捕获输出
使用 OutputCapture 来捕获指定方法开始执行以后的所有输出,包括System.out输出和Log日志。
OutputCapture 需要使用@Rule注解,并且实例化的对象需要使用public修饰,如下代码:

@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"));
}
}

关于Assert类中的一些断言方法,都很简单,本文不再赘述。

但是在新版的Junit中,assertEquals 方法已经被废弃,它建议我们使用assertArrayEquals,旨在让我们测试一个方法的时候多传几种参数进行多种可能性测试。

转自:https://yq.aliyun.com/articles/6925

spring boot单元测试(转)的更多相关文章

  1. Spring Boot单元测试(Mock)

    Spring Boot单元测试(Mock) Java个人学习心得 2017-08-12 16:07 Mock 单元测试的重要性就不多说了,我这边的工程一般都是Spring Boot+Mybatis(详 ...

  2. Spring Boot 单元测试示例

    Spring 框架提供了一个专门的测试模块(spring-test),用于应用程序的单元测试. 在 Spring Boot 中,你可以通过spring-boot-starter-test启动器快速开启 ...

  3. Spring Boot 单元测试详解+实战教程

    Spring Boot 的测试类库 Spring Boot 提供了许多实用工具和注解来帮助测试应用程序,主要包括以下两个模块. spring-boot-test:支持测试的核心内容. spring-b ...

  4. spring boot 单元测试,如何使用profile

    一.问题概述 spring boot项目.单元测试的时候,我发现,总是会使用application.properties的内容,而该文件里,一般是我的开发时候的配置. 比如上图中,dev是开发配置,p ...

  5. Java程序员的日常—— Spring Boot单元测试

    关于Spring boot 之前没有用Spring的时候是用的MockMvc,做接口层的测试,原理上就是加载applicationContext.xml文件,然后模拟启动各种mybatis\连接池等等 ...

  6. 48. spring boot单元测试restfull API【从零开始学Spring Boot】

    回顾并详细说明一下在在之前章节中的中使用的@Controller.@RestController.@RequestMapping注解.如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建 ...

  7. IDEA + Spring boot 单元测试

    1. 创建测试类 打开IDEA,在任意类名,任意接口名上,按ctrl+shift+t选择Create New Test image 然后根据提示操作(默认即可),点击确认,就在项目的/test/jav ...

  8. spring boot 单元测试 --- 在测试类使用 javabean注解操作接口

    1.依赖包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>s ...

  9. spring boot 单元测试

    Java新手 纯记录 @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = OutDemoApplication.clas ...

随机推荐

  1. WPF之鼠标滑动切换图片

    在网上找了一会儿也没找到我想要的效果,还是自己动手,丰衣足食吧. 需求:当前面板中只显示一张图片,图片栏的下部有用来显示当前图片处于图片队列中的位置的圆球,并且点击下部栏内的圆球可以快速切换,附动画缓 ...

  2. spring mvc 的各种参数的绑定方式

    本文转自http://www.cnblogs.com/HD/p/4107674.html SpringMVC的各种参数绑定方式 1. 基本数据类型(以int为例,其他类似):Controller代码: ...

  3. Android隐藏状态栏实现沉浸式体验

    转自: Android状态栏微技巧,带你真正理解沉浸式模式 什么叫沉浸式? 根据百度百科上的定义,沉浸式就是要给用户提供完全沉浸的体验,使用户有一种置身于虚拟世界之中的感觉. 那么对应到Android ...

  4. JS 获取WEB请求路径

    function getRealPath(){      //获取当前网址,如: http://localhost:8083/myproj/view/my.jsp       var curWwwPa ...

  5. 精益求精, ePub 电子书制作手记

    什么是 ePub ePub 是 Electronic Publication 的缩写,意为电子出版,是一个自由的开放标准,属于一种可以“自动重新编排”的内容,也就是文字内容可以根据阅读设备的特性,以最 ...

  6. 实现 kindle 原生系统、多看系弹出注释的通用写法

    入手 Kindle 后开始自己做 ePub,之前一直用原生系统,使用的弹出注释代码如下: <p class="P_Footnote" id="ref_footnot ...

  7. 把txt文件中的json字符串写到plist文件中

    - (void)json2Plist { NSString *filePath = [self applicationDocumentsDirectoryFileName:@"json&qu ...

  8. 抽奖随机算法的技术探讨与C#实现

    一.模拟客户需求 1.1 客户A需求:要求每次都按照下图的概率随机,数量不限,每个用户只能抽一次,抽奖结果的分布与抽奖概率近似. 1.2 客户B需求:固定奖项10个,抽奖次数不限,每个用户只能抽一次, ...

  9. oracle 数据导入导出命令

    1.数据导出:  1 将数据库TEST完全导出,用户名system 密码manager 导出到D:\daochu.dmp中   exp system/manager@TEST file=d:\daoc ...

  10. 通过Scrapy抓取QQ空间

    毕业设计题目就是用Scrapy抓取QQ空间的数据,最近毕业设计弄完了,来总结以下: 首先是模拟登录的问题: 由于Tencent对模拟登录比较讨厌,各个防备,而本人能力有限,所以做的最简单的,手动登录后 ...