Spring Boot Junit单元测试

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,旨在让我们测试一个方法的时候多传几种参数进行多种可能性测试。

时间: 2024-08-03 08:01:26

Spring Boot Junit单元测试的相关文章

【spring boot】10.spring boot下的单元测试

spring boot下的单元测试,思前想后还是需要单独用一章篇幅来看看. 然后在看了介绍和使用时候,我感觉并不想多去看了. 但是还是给后来人留下参考的路径: 官网说明:https://spring.io/blog/2016/04/15/testing-improvements-in-spring-boot-1-4[看了这篇说明,下面的问题2即可迎刃而解] 完整例子使用单元测试:https://segmentfault.com/a/1190000011420910[看了这个之后,你就打消了要把它

Maven管理的Spring Web项目集成JUnit单元测试

JUnit是一套优秀的单元测试框架,而Maven是优秀的Java项目构建和管理工具,两者结合可以很方便地对项目进行自动化测试. 一般的简单Java应用就不多说了,一些框架会提供针对junit的扩展,使得测试变得更容易,例如Spring官方就提供了spring-test,用于提供获取ApplicationContext等方面的支持. 首先要做的是,改变JUnit的实际执行类,将默认的执行类Suite替换为Spring提供的SpringJUnit4ClassRunner,也就是在测试类前面加上一个注

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

关于Spring boot 之前没有用Spring的时候是用的MockMvc,做接口层的测试,原理上就是加载applicationContext.xml文件,然后模拟启动各种mybatis\连接池等等. 后来web工程改造成了Spring boot,首先发生变化的就是配置文件,原来的xml改成了proerties或者yml.另外,原来的http接口改成了dubbo,接口层的测试就更困难了. 所以单元测试改成了直接对service层的测试,即按照原来的模式,模拟启动applicationConte

在Spring Boot项目中使用Spock框架

Spock框架是基于Groovy语言的测试框架,Groovy与Java具备良好的互操作性,因此可以在Spring Boot项目中使用该框架写优雅.高效以及DSL化的测试用例.Spock通过@RunWith注解与JUnit框架协同使用,另外,Spock也可以和Mockito(Spring Boot应用的测试--Mockito)协同使用. 在这个小节中我们会利用Spock.Mockito一起编写一些测试用例(包括对Controller的测试和对Repository的测试),感受下Spock的使用.

Spring Boot应用的测试——Mockito

Spring Boot可以和大部分流行的测试框架协同工作:通过Spring JUnit创建单元测试:生成测试数据初始化数据库用于测试:Spring Boot可以跟BDD(Behavier Driven Development)工具.Cucumber和Spock协同工作,对应用程序进行测试. 进行软件开发的时候,我们会写很多代码,不过,再过六个月(甚至一年以上)你知道自己的代码怎么运作么?通过测试(单元测试.集成测试.接口测试)可以保证系统的可维护性,当我们修改了某些代码时,通过回归测试可以检查是

Spring Boot JPA访问Mysql

上篇演示了通过Maven构建Spring Boot 项目,引用web模块启动应用,完成简单的web 应用访问,本章内容在此基础上面加入数据访问与端口修改,下文代码与演例(本用例纯手工测试通过,放心入坑). 修改默认端口 在src\**main**\resources下加入application.properties内容如下 server.port=8888 ####项目目录结构 启动应用,日志显示: 端口已经由默认的8080 变更为8888 JPA访问mysql数据库 POM中加入 <!-- S

spring boot(一):入门篇

           构建微服务:Spring boot 入门篇   什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.用我的话来理解,就是spring boot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架(不知道这样比喻是否合适).  

【spring boot】9.spring boot+spring-data-jpa的入门使用,实现数据持久化

 spring-data-jpa官方使用说明文档:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/  spring-data-jpa的使用说明:https://www.cnblogs.com/WangJinYang/p/4257383.html spring-data-jpa API地址:https://docs.spring.io/spring-data/data-jpa/docs/current/api/

Spring Boot特性

1. SpringApplication SpringApplication 类是启动 Spring Boot 应用的入口类,你可以创建一个包含 main() 方法的类,来运行 SpringApplication.run 这个静态方法: public static void main(String[] args) { SpringApplication.run(MySpringConfiguration.class, args); } 运行该类会有如下输出: . ____ _ __ _ _ /\