添加依赖

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

新建测试类

在web项目(即含有SpringApplication启动类)中test目录新建测试类, 包路径和SpringApplication中的扫描路径一致,否则无法启动测试类。若测试类的包路径和启动类的包路径不一致,会出现以下错误信息:

Neither @ContextConfiguration nor @ContextHierarchy found for test class [xx.xx.Test], using SpringBootContextLoader

Could not detect default resource locations for test class [xx.xx.Test]: no resource found for suffixes {-context.xml, Context.groovy}.

Could not detect default configuration classes for test class [xx.xx.Test]: Test does not declare any static, non-private, non-final, nested classes annotated with @Configuration.

测试类添加

package xx.xx.test;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ApplicationTests { @Before
public void init(){
System.out.println("******测试开始");
} @After
public void end(){
System.out.println("******测试结束");
} @BeforeClass
public static void initClass(){
System.out.println("******测试开始初始化");
} @AfterClass
public static void endClass(){
System.out.println("******测试结束初始化");
}
}
package xx.xx.test;

public class Test extends ApplicationTests{

    @Autowired
private BtsTradeGoodsService btsTradeGoodsService; @org.junit.Test
public void add(){
btsTradeGoodsService.add();
} }

然后在有@Test注解方法的类中使用JUint启动。 在@Test注解的方法中,和平时开发项目调用接口是一样的。

注解

类注解

@RunWith:

  1.表示运行方式,@RunWith(JUnit4TestRunner)、@RunWith(SpringRunner.class)、@RunWith(PowerMockRunner.class) 三种运行方式,分别在不同的场景中使用。

  2.当一个类用@RunWith注释或继承一个用@RunWith注释的类时,JUnit将调用它所引用的类来运行该类中的测试而不是开发者去在junit内部去构建它。我们在开发过程中使用这个特性。

@SpringBootTest:

  1.注解制定了一个测试类运行了Spring Boot环境。提供了以下一些特性:

    1.1.当没有特定的ContextConfiguration#loader()(@ContextConfiguration(loader=...))被定义那么就是SpringBootContextLoader作为默认的ContextLoader。

    1.2.自动搜索到SpringBootConfiguration注解的文件。

    1.3.允许自动注入Environment类读取配置文件。

    1.4.提供一个webEnvironment环境,可以完整的允许一个web环境使用随机的端口或者自定义的端口。

    1.5.注册了TestRestTemplate类可以去做接口调用。

  2.添加这个就能取到spring中的容器的实例,如果配置了@Autowired那么就自动将对象注入。

@WebAppConfiguration:

  由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。

@WebIntegrationTest("server.port:0"):

  使用0表示端口号随机,也可以具体指定如8888这样的固定端口。不可和@WebAppConfiguration同时使用。

方法注解

@BeforeClass:方法只能是static void。

@AfterClass:方法只能是static void。

@Before:@Test运行之前调用的方法,可以做初始化操作

@After:执行完测试用例需要执行的清理工作

@Test:测试用例的单元

@Mock:

  有点类似Autowired注解,而@Mock注解是自动实现模拟对象,而并非Bean实例创建。

  正式环境只是一个接口,并没有实现,也并没有纳入spring容器进行管理。使用BDDMockito对行为进行预测。

@Ignore("not ready yet"):该方法不执行

执行顺序是:@BeforeClass→@Before→@Test→@After→@AfterClass

当启动测试类,测试类中有多个@Test,@BeforeClass和@AfterClass只会执行一次,每一个@Test都会执行一次@Before和@After。

对Controller进行测试

  1、使用浏览器直接访问:

    http://localhost:8080/index     
    http://localhost:8080/show?id=100

  2、使用测试类:

package xx.xx.ctrl;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; @RestController
public class UserCtrl { @GetMapping("/index")
public String index(){
System.out.println("UserCtrl.index");
return "UserCtrl.index";
} @GetMapping("/show")
public String show(@RequestParam("id")String id){
System.out.println("UserCtrl.show:" + id);
return "UserCtrl.show:" + id;
}
}
package xx.xx.test;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTests { @Before
public void init(){
System.out.println("******测试开始");
} @After
public void end(){
System.out.println("******测试结束");
} @BeforeClass
public static void initClass(){
System.out.println("******测试开始初始化");
} @AfterClass
public static void endClass(){
System.out.println("******测试结束初始化");
}
}
package xx.xx.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.client.TestRestTemplate; public class Test extends ApplicationTests{ @Autowired
private TestRestTemplate testRestTemplate; @org.junit.Test
public void toIndex(){
String t = testRestTemplate.getForObject("/index", String.class);
System.out.println("toIndex:" + t);
} @org.junit.Test
public void toShow(){
String t = testRestTemplate.getForObject("/show?id=99", String.class);
System.out.println("toShow:" + t);
} @Override
public void init(){
System.out.println("******重写测试开始");
}
}

使用这种方式,在@SpringBootTest注解中一定要添加`webEnvironment = SpringBoot

SpringBoot中使用JUnit4(入门篇)的更多相关文章

  1. springboot(一)入门篇

    作者:纯洁的微笑 出处:www.ityouknow.com 版权所有,欢迎保留原文链接进行转载:) 根据原文以下内容略有调整(由于SpringBoot版本更新引起) 什么是spring boot Sp ...

  2. SpringBoot 第一篇:入门篇

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10819728.html 版权声明:本文为博主原创文章,转载请附上博文链接! 前言   博主从去年 ...

  3. Springboot快速入门篇,图文并茂

    Springboot快速入门篇,图文并茂 文章已托管到GitHub,大家可以去GitHub查看阅读,欢迎老板们前来Star!搜索关注微信公众号 [码出Offer] 领取各种学习资料! image-20 ...

  4. 【Java】在Eclipse中使用JUnit4进行单元测试(初级篇)

    本文绝大部分内容引自这篇文章: http://www.devx.com/Java/Article/31983/0/page/1 我们在编写大型程序的时候,需要写成千上万个方法或函数,这些函数的功能可能 ...

  5. 在Eclipse中使用JUnit4进行单元測试(0基础篇)

    本文绝大部分内容引自这篇文章: http://www.devx.com/Java/Article/31983/0/page/1 我们在编写大型程序的时候,须要写成千上万个方法或函数,这些函数的功能可能 ...

  6. 《Java从入门到放弃》入门篇:hibernate中的多表对应关系

    hibernate中的对应关系其实就是数据库中表的对应关系, 就跟某些电影中的某些场景是一样一样滴. 比如可以是一男一女,还可以是一男多女, 更可以是多男一女,最后最后最后还可以是多男多女!!! 有些 ...

  7. 如何在Visual Studio 2017中使用C# 7+语法 构建NetCore应用框架之实战篇(二):BitAdminCore框架定位及架构 构建NetCore应用框架之实战篇系列 构建NetCore应用框架之实战篇(一):什么是框架,如何设计一个框架 NetCore入门篇:(十二)在IIS中部署Net Core程序

    如何在Visual Studio 2017中使用C# 7+语法   前言 之前不知看过哪位前辈的博文有点印象C# 7控制台开始支持执行异步方法,然后闲来无事,搞着,搞着没搞出来,然后就写了这篇博文,不 ...

  8. SpringBoot的学习一:入门篇

    SpringBoot是什么: SpringBoot是Spring项目中的一个子工程,是一个轻量级框架. SpringBoot框架中有两个个非常重要的策略:开箱即用和约定优于配置 一.构建工程 1.开发 ...

  9. Java中的IO流 - 入门篇

    前言 大家好啊,我是汤圆,今天给大家带来的是<Java中的IO流-入门篇>,希望对大家有帮助,谢谢 由于Java的IO类有很多,这就导致我刚开始学的时候,感觉很乱,每次用到都是上网搜,结果 ...

随机推荐

  1. webpack 之 一个简单的基本生产环境配置

    webpack 之 一个简单的基本生产环境配置 // 用来拼接绝对路径的方法 const {resolve} = require('path') const HtmlWebpackPlugin = r ...

  2. PTA 7-4 最小生成树的唯一性 (35分)

    PTA 7-4 最小生成树的唯一性 (35分) 给定一个带权无向图,如果是连通图,则至少存在一棵最小生成树,有时最小生成树并不唯一.本题就要求你计算最小生成树的总权重,并且判断其是否唯一. 输入格式: ...

  3. mac 工作区

    https://www.zhihu.com/question/20917614 http://www.bjhee.com/mission-control.html 窗口切换 https://sspai ...

  4. MyScript 开发文档

    一.IInk SDK runtime 1.1 引擎创建 1.2 对象释放 1.3 获取并设置配置 配置 访问配置 配置识别 二.文件存储 2.1 支持的内容的类型 2.2 模型结构 2.3 Conte ...

  5. 获取鼠标在 canvas 中的位置

    一般情况 一般情况下,如果需要在 canvas 中获取鼠标指针坐标,可以通过监听鼠标的 mousemove(如果只需单击时的坐标,可以用 click)事件. 当事件被触发时,我们可以获取鼠标相对于 v ...

  6. ndarray 数组的创建和变换

    ndarray数组的创建方法 1.从python中的列表,元组等类型创建ndarray数组 x = np.array(list/tuple) x = np.array(list/tuple,dtype ...

  7. [luogu7468]愤怒的小N

    定义$count(x)$为$x$二进制下1的个数,答案即$\sum_{0\le x<n,count(x)\equiv 1(mod\ 2)}f(x)$ 考虑预处理出$S_{k,i,p}=\sum_ ...

  8. python中使用正则表达式处理文本(仅记录常用方法和参数)

    标准库模块 python中通过re模块使用正则表达式 import re 常用方法 生成正则表达式对象 compile(pattern[,flags]) pattern:正则表达式字符串 flags: ...

  9. 待办事项-redis

    package com.easyagu.liwei.util;import redis.clients.jedis.BinaryClient;import redis.clients.jedis.Je ...

  10. layui的入门使用

    1.如果使用单独的layui插件的话需要先引入jquery的插件,官方建议1.8+的版本. 2.引入后就能根据规则正常使用了.