SpringBoot 框架下基于 Junit 的单元测试

本案例基于  spring boot 1.5.1 junit4.1

转载:http://blog.csdn.net/tengxing007/article/details/73332038  稍作修改

前言

Junit是一个Java语言的单元测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量。是一个在发展,现在已经到junit5,在javaEE开发中与很多框架相集成,使得开发者很方便。
这里写图片描述

Junit常用注解:

  • @Before:初始化方法
  • @After:释放资源
  • @Test:测试方法,在这里可以测试期望异常和超时时间
  • @Ignore:忽略的测试方法
  • @BeforeClass:针对所有测试,只执行一次,且必须为static void
  • @AfterClass:针对所有测试,只执行一次,且必须为static void
  • @RunWith:指定使用的单元测试执行类

Junit测试用例执行顺序:

@BeforeClass ==> @Before ==> @Test ==> @After ==> @AfterClass
过程:就是先加载模拟的环境,再进行测试

测试准备

依赖版本(不同版本存在一些差异)

  • junit 4.12
  • spring-test 4.3.6
  • spring-boot-test 1.5.1

添加依赖(必须)

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <version> 1.5.1.RELEASE</version>
    </dependency>

编辑器(非必须)

IntellijIDEA

测试代码

测试代码如下:

import cn.yjxxclub.springboot.entity.Member;
import cn.yjxxclub.springboot.mapper.MemberMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: 遇见小星
 * Email: [email protected]
 * Date: 17-6-16
 * Time: 下午12:18
 * Describe: member应用测试类
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MemberTest {

    /**
     * Spring RestTemplate的便利替代。你可以获取一个普通的或发送基本HTTP认证(使用用户名和密码)的模板
     * 这里不使用
     */
    @Autowired
    private TestRestTemplate testRestTemplate;

    @Autowired
    MemberMapper memberMapper;


    /**
     * 2017-06-16 14:08:09.884  INFO 13803 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
     size:5
     -----测试完毕-------
     2017-06-16 14:08:09.955  INFO 13803 --- [       Thread-4] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@fd07cbb: startup date [Fri Jun 16 14:08:04 CST 2017]; root of context hierarchy
     */
    @Test
    public void test(){
        Map<String,Object> map = new HashMap();
        map.put("start",0);
        map.put("size",8);
        List<Member> list = memberMapper.list(map);
        System.out.println("size:"+list.size());
        System.out.println("-----测试完毕-------");

    }
}

代码说明

  • @RunWith 是junit提供的,前言已经说了
  • SpringRunner是spring-test提供的测试执行单元类(SpringJUnit4ClassRunner的新名字)
    这里写图片描述
  • @SpringBootTest is saying “bootstrap with Spring Boot’s support”,类似springboot程序的测试引导入口
    具体请看spring.io解释:
    这里写图片描述

猜你喜欢

转载自j2ees.iteye.com/blog/2400036