Intellij IDEA中添加JUnit4/5單元測試


Intellij IDEA中添加JUnit單元測試

一、下載jar

首先需要去下載JUnit的jar包以及一個依賴包hamcrest.core,例如:
junit:junit:4.13-beta-1
hamcrest.core:1.3.0.1
需要注意的是hamcrest.core包不能使用2.1版本的,因為4.13版本的JUnit和它不兼容,會拋出ClassNotFoundException異常。

 

推薦使用 junit-4.13.jar 和 hamcrest-core-1.3.jar ,可以使用 https://jar-download.com/  下載

二、在Intellij IDEA項目中添加jar

首先需要在IDEA中添加剛才下載好的包:

 

 

 

三、下載插件並進行設置

然后需要下載一個名為JUnitGeneratorV2.0的插件:

然后對其進行設置:

 

四、創建存放測試文件的目錄

1.使用快捷鍵alt+insert創建的test類

 

通過 JUnitGenetor插件,使用Alt+Insert快捷鍵自動生成當前類的所有方法的測試單元時,自動生成的 .java 文件的存放目錄,即使:

 

2.使用快捷鍵Ctrl+Shift+T創建的test類

創建文件夾指定類型為Tests

 

 

 

 

如果是使用Ctrl+Shift+T快捷鍵自定義需要測試的方法,則生成的文件會存放於指定的存放測試文件的目錄

  

將圖片中的$data改為$today是為了防止生成的測試類產生亂碼。

 

 

 


五、創建Test用例

1.前提:原始類

public class Calculate {
   
    public static int add(int a, int b) {
        return a + b;
    }

    public static int substract(int a, int b) {
        return a - b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }

    public static int divide(int a, int b) {
        return a / b;
    }
}

 

2. (Junit4)使用快捷鍵alt+insert創建的test類

package test.com.panta;

import com.panta.Calculate;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
* Calculate Tester.
*
* @author <haokun>
* @since <pre>08/11/2020</pre>
* @version 1.0
*/
public class CalculateTest {

@Before
public void before() throws Exception {
    System.out.println("測試開始");
}

@After
public void after() throws Exception {
    System.out.println("測試結束");
}

/**
*
* Method: add(int a, int b)
*
*/
@Test
public void testAdd() throws Exception {
    assertEquals(8, Calculate.add(2, 6));
}

/**
*
* Method: substract(int a, int b)
*
*/
@Test
public void testSubstract() throws Exception {
    assertEquals(7,Calculate.substract(9,2));
}

/**
*
* Method: multiply(int a, int b)
*
*/
@Test
public void testMultiply() throws Exception {
    assertEquals(15,Calculate.multiply(3, 5));
}

/**
*
* Method: divide(int a, int b)
*
*/
@Test
public void testDivide() throws Exception {
    assertEquals(2,Calculate.divide(4, 2));
}
}

運行結果:

 

 

 

3. (Junit4)使用快捷鍵Ctrl+Shift+T創建的test類

package com.panta;

import org.junit.*;

import static org.junit.Assert.assertEquals;

public class CalculateTest {
   
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("this is beforeClasss....");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("this is afterClasss....");
    }

    @Before
    public void before() throws Exception {
        System.out.println("測試開始");
    }

    @After
    public void after() throws Exception {
        System.out.println("測試結束");
    }

    @Test
    public void testadd(){
        assertEquals(6,new Calculate().add(3, 3));
    }

    @Test
    public void testsubstract(){
        assertEquals(2,new Calculate().substract(5, 3));
    }

    @Test
    public void testmultiply(){
        assertEquals(15,new Calculate().multiply(5, 3));
    }
    @Test
    public void testdivide() {
        assertEquals(2, new Calculate().divide(6, 3));
    }
    @Ignore
    public void testdivide1() {
        assertEquals(2, new Calculate().divide(6, 3));
        System.out.println("this is divideClasss....");
    }

}

運行結果:

 

 

 

4.總結:

@BeforeClass

修飾的方法會在所有方法被調用前執行,且該方法時靜態的,所以當測試類被加載后就接着運行它,而且在內存中他只會存在一份實例,他比較適合加載配置文件(針對所有測試,只執行一次 )

@AfterClass

所修飾的方法通常用來對資源管理,如關閉數據庫連接(針對所有測試,只執行一次 )

@Before和@After 會在每個測試方法前后各執行一次

@Test:測試方法,在這里可以測試期望異常和超時時間

@Ignore:忽略的測試方法

----------------------------------------------------------------------------------------------

 

1.測試方法上必須使用@Test

2.測試方法必須使用 public void進行修飾

 

3.新建一個源代碼目錄來存放測試代碼

4.測試類的包應該和被測試類的包一樣

5.測試單元中的每個方法一定要能夠獨立測試,其方法不能有任何依賴

 

 

六、junit 測試套件Suite

1.創建2個測試函數:

package test.com.panta;

import com.panta.Calculate;
import org.junit.*;

import static org.junit.Assert.assertEquals;

public class CalculateTest1 {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("CalculateTest1:this is beforeClasss....");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("CalculateTest1:this is afterClasss....");
    }

    @Before
    public void before() throws Exception {
        System.out.println("CalculateTest1測試開始");
    }

    @After
    public void after() throws Exception {
        System.out.println("CalculateTest1測試結束");
    }

    @Test
    public void testdivide1() {
        assertEquals(2, new Calculate().divide(6, 3));
        System.out.println("CalculateTest1:this is divideClasss....");
    }

}

 

 

package test.com.panta;

import com.panta.Calculate;
import org.junit.*;

import static org.junit.Assert.assertEquals;

public class CalculateTest2 {

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        System.out.println("CalculateTest2:this is beforeClasss....");
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        System.out.println("CalculateTest2:this is afterClasss....");
    }

    @Before
    public void before() throws Exception {
        System.out.println("CalculateTest2測試開始");
    }

    @After
    public void after() throws Exception {
        System.out.println("CalculateTest2測試結束");
    }

    @Test
    public void testdivide1() {
        assertEquals(2, new Calculate().divide(6, 3));
        System.out.println("CalculateTest2:this is divideClasss....");
    }

}

 

2.把2個測試函數加入Suite:

package test.com.panta;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)   //@RunWith表示這個類將以哪種形式來跑
@Suite.SuiteClasses({    //@Suite.SuiteClasses則可以包含多個test unit
       
CalculateTest1.class,
        CalculateTest2.class
})
public class SuiteTest {

    /**
     * 1.
測試套件就是組織測試類一起運行的
    
*
     *
寫一個作為測試套件的入口類,這個類里不包含其他的方法
    
* 更改測試運行器Suite.classes,將要測試的類作為數組傳入到Suite.SuiteClasses({})
     */

}

 

 

查看運行結果:

 

 

七、報告生成

1、環境准備

Intellij IDEA

JUnit4

1.1.安裝 Ant

直接在官網下載最新的 Ant 即可https://downloads.apache.org/ant/binaries/

 

 

 1.2.配置 Ant

  在系統環境變量的 Path 中添加 Ant 路徑。例如我的路徑為 E:\JetBrains\apache-ant-1.10.8\bin

1.3.測試 Ant 是否配置成功

  在 cmd 中輸入 ant -version,顯示版本信息即正確。

 

 

 

2、編寫測試代碼

2.1.在 src 目錄下編寫測試類

package cn;

public class Calculate {

    private static int a;
    private static int b;

    public static int add(int a, int b) {
        return a + b;
    }

    public static int substract(int a, int b) {
        return a - b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }

    public static int divide(int a, int b) {
        return a / b;
    }

}

 

2.2在 test 目錄(如果沒有則新建 Test ,並且將其設置為 Test Sources Root)下編寫測試類

 

 

 

package cn;

import org.junit.Assert;
import org.junit.Test;

public class TestCalculate {

    @Test
    public void testAdd() throws Exception {
        Assert.assertEquals(8,Calculate.add(2, 6));
    }

    @Test
    public void substract() throws Exception {
        Assert.assertEquals(7,Calculate.substract(9,2));
    }

    @Test
    public void testMultiply() throws Exception {
        Assert.assertEquals(15,Calculate.multiply(3, 5));
    }
    @Test
    public void testDivide() throws Exception {
        Assert.assertEquals(2,Calculate.divide(4, 2));
    }

}

 

3、編寫 Ant 配置文件

  一般配置文件命名為 build.xml ,在項目根目錄下創建配置文件 build.xml ,然后在界面右側靠邊處選擇 【Ant】,點擊后選擇 【+】 添加該文件到 Ant 中。

 

build.xml  內容如下:

<?xml version="1.0"?>

<project name="ant and junit" default="test auot junit and report" basedir=".">

    <!-- 定義工程依賴的jar包存放的位置 -->
    <property name="lib.dir" value="lib"/>
    <path id="classpath">
        <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>

    <property name="output folder" value="classes"/>
    <property name="src folder" value="src"/>
    <property name="test folder" value="test"/>
    <property name="report folder" value="report"/>

    <target name="clean">
        <delete dir="report"/>
        <echo>清除測試報告文件 成功!</echo>
    </target>

    <target name="compile init">
        <mkdir dir="${output folder}"/>
        <echo>創建編譯文件夾 成功!</echo>
    </target>

    <target name="report init" depends="clean">
        <mkdir dir="${report folder}"/>
        <echo>創建測試報告文件夾 成功!</echo>
    </target>

    <target name="compile" depends="compile init">
        <javac srcdir="${src folder}" destdir="${output folder}" classpathref="classpath"/>
        <echo>項目源文件編譯 成功!</echo>
    </target>

    <target name="test compile" depends="report init">
        <javac srcdir="${test folder}" destdir="${output folder}" classpathref="classpath"/>
        <echo>項目測試文件編譯 成功!</echo>
    </target>

    <target name="all compile" depends="compile, test compile">
    </target>

    <target name="test auot junit and report" depends="all compile">
        <junit printsummary="on" fork="true" showoutput="true">
            <classpath>
                <fileset dir="${lib.dir}" includes="**/*.jar"/>
                <pathelement path="${output folder}"/>
            </classpath>
            <formatter type="xml"/>
            <batchtest todir="${report folder}">
                <fileset dir="${output folder}">
                    <include name="**/Test*.*"/>
                </fileset>
            </batchtest>
        </junit>
        <junitreport todir="${report folder}">
            <fileset dir="${report folder}">
                <include name="TEST-*.xml"/>
            </fileset>
            <report format="frames" todir="${report folder}"/>
        </junitreport>
    </target>

</project>

 

另外:pom.xml添加信息

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>1</groupId>
    <artifactId>1</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.vcplatform.test</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/lib/testng-6.11.jar</systemPath>
        </dependency>

    </dependencies>


</project>

 

4、運行結果

4.1.項目目錄結構

  在項目運行時需要單獨的 JUnit.jar ,所以需要先在項目根目錄下創建 lib 文件夾,並將 JUnit.jar 放入其中。

 

4.2.選擇該 Ant 類,點擊運行即可,如果測試正確會在終端顯示正常編譯結果。

 

4.3.在瀏覽器中輸入 項目的路徑/report/index.html 可以查看 Ant 自動化測試的報告結果。

 

 

 

八、Junit5

Pom.xml 添加依賴

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.5.0</version>
    <scope>test</scope>
    <systemPath>${project.basedir}/lib/junit-platform-launcher-1.5.0.jar</systemPath>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.6.2</version>
    <scope>test</scope>
    <systemPath>${project.basedir}/lib/junit-jupiter-engine-5.6.2.jar</systemPath>
</dependency>
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <version>5.6.2</version>
    <scope>test</scope>
    <systemPath>${project.basedir}/lib/junit-vintage-engine-5.6.2.jar</systemPath>
</dependency>

並把對應的jar放在路徑中,jar可以在這里下載:https://mvnrepository.com/artifact/org.junit.vintage/junit-vintage-engine/5.6.2

 

 

 

運行一個:

 

 

 

package cn;

import org.junit.Assert;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertAll;

import org.junit.jupiter.api.*;

import static org.junit.jupiter.api.Assertions.*;

class CalculateTest5 {

    @Test
    void add() throws Exception{
        Assert.assertEquals(8,Calculate.add(2, 6));

    }

}

 

運行結果:

 

 

 

 

對比Junit4,有幾個特點:

導入測試測試注解(@Test)和斷言方法(assertEquals)的路徑不同。其次,不需要手動把測試和測試方法聲明為 public

沒有發現有什么特別的,忽略掉


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM