添加依赖

<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. mac 工作区

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

  2. 为什么不直接去Arraylist list = new Arraylist();而是直接通过List list = new ArrayList();使用接口的好处

    ArrayList不是继承List接口,是实现了List接口. 你写成ArrayList arrayList = new ArrayList();这样不会有任何问题.和List list = new ...

  3. 大一C语言学习笔记(1)---编译顺序问题;不同数据类型赋值,运算问题;算数运算符易错点(以解一元二次方程为例)

    废话少说,上代码: #include<stdio.h> #include<math.h> int main()//解一元二次方程 { int a,b,c; double too ...

  4. AsExpandable EF多条件查询

    我个人学习新技术有一个方法,如果遇到问题会根据以前的经验来寻找一些类似的解决方法.有人会说,如果这个问题在你的学习或者工作生涯中都没有遇到过呢?很简单,通过搜索资料或查阅相关书籍学习别人的经验. 在如 ...

  5. excel (2)

    ... poi 3.8 import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; ...

  6. 痞子衡嵌入式:深扒IAR启动函数流程及其__low_level_init设计对函数重定向的影响

    大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家分享的是IAR启动函数流程及其__low_level_init设计对函数重定向的影响. 上一篇文章 <IAR下RT-Thread工程自定义 ...

  7. element ui tree回显 setCheckedNodes,setCheckedKeys,setChecked等函数报undefined问题

    在写项目的时候,需要用到tree组件进行回显来进行权限控制: 在回显过程中使用回显函数会报报undefined, 这时只需要给该函数包裹一层nextTick方法就行了, 在回显过程中我们有可能使用半选 ...

  8. tomcat隐藏版本号

    默认报错页面信息会暴露出版本号 进入tomcat的lib目录找到catalina.jar文件 unzip catalina.jar之后会多出两个文件夹 进入org/apache/catalina/ut ...

  9. java中static关键字的解析

    静态的特点: A:随着类的加载而加载 B:优先于对象而存在 C:静态是被所有对象共享的数据 这也是我们来判断是否使用静态的标准 D:静态的出现,让我们的调用方式多了一种 类名.静态的内容 非静态的内容 ...

  10. [hdu7012]Miserable Faith

    类似于[NOI2021]轻重边的逆过程,操作1即为对$u$​执行access(根为1),$dist(u,v)$​即为$u$​到$v$​的虚边数 对前者用LCT维护,并记录轻重边的切换,显然切换总量为$ ...