Spring Boot学习之旅:(五)Spring Boot 使用 junit 单元测试
2017-10-06 23:18
706 查看
最近刚好时间写了一些关于SpringBoot的帖子,正好现在把Junit再拿出来从几个方面再说一下。
那么先简单说一下为什么要写测试用例
1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率
2. 可以自动测试,可以在项目打包前进行测试校验
3. 可以及时发现因为修改代码导致新的问题的出现,并及时解决
那么本文从以下几点来说明怎么使用Junit,Junit4比3要方便很多,细节大家可以自己了解下,主要就是版本4中对方法命名格式不再有要求,不再需要继承TestCase,一切都基于注解实现。
因为我们是Web项目,所以在创建的Java类中添加注解:
接下来就可以编写测试方法了,测试方法使用@Test注解标注即可。
在该类中我们可以像平常开发一样,直接@Autowired来注入我们要测试的类实例。
可以创建一个baseTest将上述的配置放入进去,子类的单元测试只需要继承他即可。
下面写一个单元测试的简单的例子
如果输出hello则成功了
@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来运行你的代码。
然而因为Junit 使用@RunWith指定一个Runner,在我们更多情况下需要使用@RunWith(SpringJUnit4ClassRunner.class)来测试我们的Spring工程方法,所以我们使用assertArrayEquals 来对方法进行多种可能性测试便可。
下面是关于参数化测试的一个简单例子:
打包测试,就是新增一个类,然后将我们写好的其他测试类配置在一起,然后直接运行这个类就达到同时运行其他几个测试的目的。
代码如下:
下面是一个简单的例子:
OutputCapture 需要使用@Rule注解,并且实例化的对象需要使用public修饰,如下代码:
文章地址:http://www.haha174.top/article/details/254599
源码地址:https://github.com/haha174/boot.git
那么先简单说一下为什么要写测试用例
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 = App.class) // 指定我们SpringBoot工程的Application启动类 @WebAppConfiguration // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
接下来就可以编写测试方法了,测试方法使用@Test注解标注即可。
在该类中我们可以像平常开发一样,直接@Autowired来注入我们要测试的类实例。
可以创建一个baseTest将上述的配置放入进去,子类的单元测试只需要继承他即可。
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=App.class) @WebAppConfiguration public class BaseTest { }
下面写一个单元测试的简单的例子
@Component @ConfigurationProperties(prefix = "wen") public class ConfigString { private String hello; private String world; /** * @return the hello */ public String getHello() { return hello; } /** * @param hello the hello to set */ public void setHello(String hello) { this.hello = hello; } /** * @return the world */ public String getWorld() { return world; } /** * @param world the world to set */ public void setWorld(String world) { this.world = world; } }
public class JunitTest extends BaseTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired ConfigString ConfigString; @Test public void RedisTest() throws Exception { System.out.println(ConfigString.getHello()); } }
如果输出hello则成功了
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 com.wen.test; 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); } @Parameters public static Collection<?> data(){ // Object 数组中值的顺序注意要和上面的构造方法ParameterTest的参数对应 return Arrays.asList(new Object[][]{ {"小明", true}, {"小红", false}, {"小莉", false}, }); } }
4、打包测试
正常情况下我们写了3个测试类,我们需要一个一个执行。打包测试,就是新增一个类,然后将我们写好的其他测试类配置在一起,然后直接运行这个类就达到同时运行其他几个测试的目的。
代码如下:
package com.wen.test; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ParameterTest.class, JunitTest.class}) public class PackageTest { // 类中不需要编写代码 }
5、使用Junit测试HTTP的API接口
我们可以直接使用这个来测试我们的Rest API,如果内部单元测试要求不是很严格,我们保证对外的API进行完全测试即可,因为API会调用内部的很多方法,姑且把它当做是整合测试吧。下面是一个简单的例子:
package com.wen.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.wen.boot.App; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=App.class) @WebAppConfiguration public class HelloControllerTest { private static final Logger logger = LoggerFactory.getLogger(HelloControllerTest.class); private RestTemplate template = new RestTemplate(); @Test public void test3(){ try { String url = "http://localhost:8082/hello/test.do"; MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); map.add("name", "Tom"); String result = template.postForObject(url, map, String.class); System.out.println(result); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
6、捕获输出
使用 OutputCapture 来捕获指定方法开始执行以后的所有输出,包括System.out输出和Log日志。OutputCapture 需要使用@Rule注解,并且实例化的对象需要使用public修饰,如下代码:
package com.wen.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.hamcrest.Matchers; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.rule.OutputCapture; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.wen.boot.App; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=App.class) @WebAppConfiguration public class HelloControllerTest { private static final Logger logger = LoggerFactory.getLogger(HelloControllerTest.class); private RestTemplate template = new RestTemplate(); @Test public void test3(){ try { String url = "http://localhost:8082/hello/test.do"; MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); map.add("name", "Tom"); String result = template.postForObject(url, map, String.class); System.out.println(result); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
@Rule
// 这里注意,使用@Rule注解必须要用public
public OutputCapture capture = new OutputCapture();
@Test
public void test4(){
System.out.println("HelloWorld");
logger.info("logo日志也会被capture捕获测试输出");
}
}
文章地址:http://www.haha174.top/article/details/254599
源码地址:https://github.com/haha174/boot.git
相关文章推荐
- Spring Boot---(11)SpringBoot使用Junit单元测试
- 使用JUnit 对 Spring Boot REST API 执行单元测试
- SpringBoot 学习记录(三)- Junit 单元测试
- Spring 使用Junit 进行单元测试
- Spring整合JUnit框架进行单元测试代码使用详解
- [转][Java]使用Spring配合Junit进行单元测试的总结
- 在Myeclipse里使用Junit贴图教程与使用JUnit在struts+spring+hibernate框架环境下进行单元测试
- 使用JUnit在struts+spring+hibernate框架环境下进行单元测试
- Spring整合JUnit框架进行单元测试代码使用详解
- 使用Junit4对由Maven管理的Spring项目进行单元测试
- (软件项目管理)在eclipse里使用junit进行单元测试以及Maven的学习
- Spring Boot 官方文档学习(一)入门及使用
- 使用JUnit在struts+spring+hibernate框架环境下进行单元测试
- maven下使用 junit对 spring进行单元测试
- Spring项目中使用Junit单元测试并配置数据源的问题
- 使用spring配合Junit进行单元测试的总结
- Eclipse学习4-在Eclipse中使用JUnit进行单元测试(上)
- JUnit4学习笔记2-Eclipse中使用JUint4进行单元测试
- Spring Boot学习笔记-SQL数据库使用
- 使用JUnit在struts+spring+hibernate框架环境下进行单元测试