springboot Junit 执行顺序详解

目录
  • springboot Junit 执行顺序
  • SpringBoot JUnit 测试 Controller

springboot Junit 执行顺序

我们在写JUnit测试用例时,有时候需要按照定义顺序执行我们的单元测试方法,比如如在测试数据库相关的用例时候要按照测试插入、查询、删除的顺序测试。

如果不按照这个顺序测试可能会出现问题,比如删除方法在前面执行,后面的方法就都不能通过测试,因为数据已经被清空了。而JUnit测试时默认的顺序是随机的。

所以这时就需要有办法要求JUnit在执行测试方法时按照我们指定的顺序来执行。

JUnit是通过@FixMethodOrder注解(annotation)来控制测试方法的执行顺序的。

@FixMethodOrder注解的参数是org.junit.runners.MethodSorters对象,在枚举类org.junit.runners.MethodSorters中定义了如下三种顺序类型:

  • MethodSorters.JVM

Leaves the test methods in the order returned by the JVM. Note that the order from the JVM may vary from run to run (按照JVM得到的方法顺序,也就是代码中定义的方法顺序)

  • MethodSorters.DEFAULT(默认的顺序)

Sorts the test methods in a deterministic, but not predictable, order() (以确定但不可预期的顺序执行)

  • MethodSorters.NAME_ASCENDING

Sorts the test methods by the method name, in lexicographic order, with Method.toString() used as a tiebreaker (按方法名字母顺序执行)

举例说明

以下的代码,定义了三个方法testAddAndGet,testSearch,testRemove,我设计的时候,是希望三个方法按定义的顺序来执行。

package test;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@FixMethodOrder(MethodSorters.JVM)//指定测试方法按定义的顺序执行
public class TestJNI {
    private static final Logger logger = LoggerFactory.getLogger(TestJNI.class);
    @Test
    public void testAddAndGet(){
        logger.info("test 'addBean' and 'getBean' ");
    }

    @Test
    public final void testSearch() {
        logger.info("test search CODE from JNI memory...");
    }
    @Test
    public final void testRemove() {
        logger.info("test remove CODE from JNI memory...");
    }
}

如果@FixMethodOrder定义为MethodSorters.DEFAULT或去掉代码中的@FixMethodOrder注解,那么测试用便执行的顺序是

这并不是我要的结果,testRemove如果先执行了,testSearch肯定什么也找不到。

如果改成@FixMethodOrder(MethodSorters.JVM),则这个执行顺序才是我想要的顺序。

SpringBoot JUnit 测试 Controller

Controller层代码如下:

@RestController
public class HelloController {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UserService userService;
    @RequestMapping("/hello")
    public String index() {
        logger.info("{}",userService == null);
        logger.info("{}",userService.getCount());
        return "Hello World";
    }
}

JUnit 测试HelloController代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloControllerTest {
    private MockMvc mvc;
    @Before
    public void setUp() throws Exception {
        mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
    }
    @Test
    public void getHello() throws Exception {
    mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}

但是这种方法在运行过程中,Controller 里面Autowired 的bean 无法注入,报空指针,因为这种方法没有给通过Spring加载上下文实现注入参考这里的解决方法

采取下面这种测试写法

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @Test
    public void getHello() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andReturn();
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring Boot通过Junit实现单元测试过程解析

    这篇文章主要介绍了Spring Boot通过Junit实现单元测试过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.需要在pom.xml中引入spring-boot-starter-test <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifa

  • SpringBoot整合Junit实例过程解析

    这篇文章主要介绍了SpringBoot整合Junit实例过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 前提条件:SpringBoot已经整合了Mybatis,至于SpringBoot如何整合Mybatis可参考SpringBoot整合mybatis简单案例过程解析 SpringBoot为什么要整合Juni? SpringBoot整合了Junit后,在写了Mapper接口后,可直接通过Junit进行测试,不用再写Controller层,

  • Spring Boot 单元测试JUnit的实践

    一.介绍 JUnit是一款优秀的开源Java单元测试框架,也是目前使用率最高最流行的测试框架,开发工具Eclipse和IDEA对JUnit都有很好的支持,JUnit主要用于白盒测试和回归测试. <!--more--> 白盒测试:把测试对象看作一个打开的盒子,程序内部的逻辑结构和其他信息对测试人 员是公开的: 回归测试:软件或环境修复或更正后的再测试: 单元测试:最小粒度的测试,以测试某个功能或代码块.一般由程序员来做,因为它需要知道内部程序设计和编码的细节: JUnit GitHub地址:ht

  • 在Spring boot的项目中使用Junit进行单体测试

    使用Junit或者TestNG可以进行单体测试,这篇文章简单说明一下如何在Spring boot的项目中使用Junit进行单体测试. pom设定 pom中需要添加spring-boot-starter-test <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>

  • springboot Junit 执行顺序详解

    目录 springboot Junit 执行顺序 SpringBoot JUnit 测试 Controller springboot Junit 执行顺序 我们在写JUnit测试用例时,有时候需要按照定义顺序执行我们的单元测试方法,比如如在测试数据库相关的用例时候要按照测试插入.查询.删除的顺序测试. 如果不按照这个顺序测试可能会出现问题,比如删除方法在前面执行,后面的方法就都不能通过测试,因为数据已经被清空了.而JUnit测试时默认的顺序是随机的. 所以这时就需要有办法要求JUnit在执行测试

  • 对for循环中表达式和循环体的执行顺序详解

    对于学c的朋友来说,for循环可能使我们经常用到的一种循环语句 for(表达式1:表达式2:表达式3){循环体} 知道其的语句执行顺序对我们来说可以避免很多失误 我们可以利用下面这个小程序轻易测出其内在的语句循环顺序: #include<stdio.h> void main() { int i; for (printf("#1\n"),i=1; printf("#2\n"),i<=5; printf("#3\n"),i++) {

  • vue中各选项及钩子函数执行顺序详解

    在vue中,实例选项和钩子函数和{{}}表达式都是不需要手动调用就可以直接执行的. vue的生命周期如下图: 在页面首次加载执行顺序有如下: beforeCreate //在实例初始化之后.创建之前执行 created //实例创建后执行 beforeMounted //在挂载开始之前调用 filters //挂载前加载过滤器 computed //计算属性 directives-bind //只调用一次,在指令第一次绑定到元素时调用 directives-inserted //被绑定元素插入父

  • 基于Laravel 多个中间件的执行顺序详解

    问题 一个路由需要用到多个中间件,其中一个是 Laravel 自带的 auth 中间件. 发现这个中间件不管放在哪里,总是在自定义中间件之前执行. 如果业务需要自定义中间在 auth 之前执行,还是有办法的. 解决方案 观察定义中间件的 app\Http\Kernel 类,是继承的 Illuminate\Foundation\Http\Kernel 类. 再打开 Illuminate\Foundation\Http\Kernel ,发现有这样一个数组 ... /** * The priority

  • 对python中的try、except、finally 执行顺序详解

    如下所示: def test1(): try: print('to do stuff') raise Exception('hehe') print('to return in try') return 'try' except Exception: print('process except') print('to return in except') return 'except' finally: print('to return in finally') return 'finally'

  • java异常处理执行顺序详解try catch finally

    目录 不含return的执行顺序 finally子句 含return的执行顺序 返回类型是对象类型时值的变化 结论 不含return的执行顺序 执行顺序为执行try中代码,如果没有异常,然后执行try catch后续的代码.如: public static void main(String[] args) { try { int j = 10 / 2; System.out.println("执行try中代码!"); } catch (Exception e) { e.printSta

  • Mysql系列SQL查询语句书写顺序及执行顺序详解

    目录 1.一个完整SQL查询语句的书写顺序 2.一个完整的SQL语句执行顺序 3.关于select和having执行顺序谁前谁后的说明 1.一个完整SQL查询语句的书写顺序 -- "mysql语句编写顺序" 1 select distinct * 2 from 表(或结果集) 3 where - 4 group by -having- 5 order by - 6 limit start,count -- 注:1.2属于最基本语句,必须含有. -- 注:1.2可以与3.4.5.6中任一

  • vue中created、watch和computed的执行顺序详解

    目录 前言 为什么? 1.关于initComputed 2.关于initWatch 总结 前言 面试题:vue中created.watch(immediate: true)和computed的执行顺序是啥? 先看个简单的例子: // main.js import Vue from "vue"; new Vue({ el: "#app", template: `<div> <div>{{computedCount}}</div> &

  • Spring Aop常见注解与执行顺序详解

    目录 Spring Aop 的常用注解 常见问题 示例代码 配置文件 接口类 实现类 aop 拦截器 测试类 执行结论 多切面的情况 代理失效场景 总结 Spring 一开始最强大的就是 IOC / AOP 两大核心功能,我们今天一起来学习一下 Spring AOP 常见注解和执行顺序. Spring Aop 的常用注解 首先我们一起来回顾一下 Spring Aop 中常用的几个注解: @Before 前置通知:目标方法之前执行 @After 后置通知:目标方法之后执行(始终执行) @After

  • java面试题之try中含return语句时代码的执行顺序详解

    前言 最近在刷java面试题偶然看到这类问题(try/finally中含有return时的执行顺序),觉得挺有意思于是小小的研究了一下,希望经过我添油加醋天马行空之后,能给你带来一定的帮助,下面来看看详细的介绍. 原题 try {} 里有一个return语句,那么紧跟在这个try后的finally {}里的代码会不会被执行?什么时候被执行?在return前还是后? 乍一看题目很简单嘛,java规范都说了,finally会在try代码块的return之前执行,你这文章写得没意义,不看了 你等等!(

随机推荐