• 关于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注解
    在这里插入图片描述

  • 相关阅读:
    基于stm32单片机ADC采集电压表测量LCD1602显示
    Java学习笔记(三十)
    RabbitMQ实现秒杀场景示例
    JavaScript学习笔记
    study
    性能优化:TCP连接优化之三次握手
    ESP8266 Node Mcu开发板连接WIFI并上报数据到MQTT服务器——物联网应用开发
    echarts简单的圆角圆环实现
    docker容器持久化
    Linux 之 openssl 文件夹加密压缩与解压
  • 原文地址:https://blog.csdn.net/nvd11/article/details/126577137