• 关于Junit的一些问题


    1. 关于@Test 注解, 到底引用 import org.junit.jupiter.api.Test 还是 org.junit.Test?

    答案:
    org.junit.jupiter.api.Test 是Junit5
    org.junit.Test 是Junit4.

    建议Junit5


    2. @RunWith(SpringRunner.class) 与 @SpringBootTest的区别

    答案:
    @RunWith 是Junit4的东西
    @SpringBootTest 是spring framework 里的东西

    如果使用Junit4, 两者都需要, 如果使用Junit5, 只使用@SpringBootTest就够了, 使用@RunWith反而会报错

    org.junit.runners.model.InvalidTestClassError: Invalid test class 'cn.itcast.order.TestCase1':
      1. No runnable methods
    
    	at org.junit.runners.ParentRunner.validate(ParentRunner.java:525)
    	at org.junit.runners.ParentRunner.<init>(ParentRunner.java:92)
    	at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:74)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6



    3. 怎样在Junit里指定spring 配置文件. (旧项目里的spring-context.xml…)

    答案:

    @RunWith(SpringJUnit4ClassRunner.class)
    // ApplicationContext will be loaded from "classpath:/app-config.xml"
    @ContextConfiguration("/app-config.xml")
    
    • 1
    • 2
    • 3

    参考:
    https://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles



    4.Springboot 指定运行环境(哪个配置文件)

    答案:

    @SpringBootTest()
    @ActiveProfiles("uat")
    public class TestCase1 {
    
    • 1
    • 2
    • 3



    5.@Before @BeforeClass @BeforeEach @BeforeAll 到底有什么区别

    @Before 会在每次测试方法前执行
    @BeforeClass 会在单元测试类被执行时执行, for 1个class只会执行一次

    上面两个注解是Junit4的
    到了Junit5
    改成了
    @BeforeEach
    @BeforeAll



    6. 如何為Junit 指定環境變量

    实际例子:
    Spring Cloud config 需要的ENCRYPT_KEY 变量

    答案:
    本人已經在google查過很多方法。

    唯一有效方法的就是放弃这个配置放入项目代码:

    solution:
    IDE: 为每一次测试用力加上环境变量参数
    在这里插入图片描述
    自动化:
    在执行mvn test之前
    设置环境变量
    例如:

    set "ENCRYPT_KEY=xxxx" && mvn test
    
    • 1



    7.如何改變測試方法的顯示名字?

    主要是給別人(你老闆)看的
    在这里插入图片描述

    答案:
    使用@DisplayName注解

      @Test
        @DisplayName("dummy testing case")
        public void test1(){
    
    • 1
    • 2
    • 3

    在这里插入图片描述



    8.如何期待测试方法会抛出1个expected 异常?

    答案:
    使用assertThrow()
    在这里插入图片描述

    9. 指定某个类测试方法的顺序?

    答案:
    使用@TestMethodOrder注解
    在这里插入图片描述

  • 相关阅读:
    3.Java线程的状态
    C++学习笔记(1)--递归引入
    Vue系列(四)之 Vue路由介绍和Node.js的环境搭建
    TimescaleDB 开源时序数据库
    zabbix6.0 部署配置
    flink源码分析 - 获取调用位置信息
    物流通知:您的快递即刻送达!
    netty系列之:让TCP连接快一点,再快一点
    《数据结构与算法》-栈的概念和栈的实现
    壳聚糖-聚乙二醇-醛基|醛基-PEG-壳聚糖|甲苯磺酸酯,氨甲基修饰壳聚糖
  • 原文地址:https://blog.csdn.net/nvd11/article/details/126577137