TestNG忽略測試

有時,我們編寫的代碼並沒有準備就緒,並且測試用例要測試該方法/代碼是否失敗(或成功)。 在本示例中,註釋[@Test](https://github.com/Test "@Test")(enabled = false)有助於禁用此測試用例。

如果使用[@Test](https://github.com/Test "@Test")(enabled = false)註釋在測試方法上,則會繞過這個未準備好測試的測試用例。

在本教程中,我們將演示如何使用[@Test](https://github.com/Test "@Test")(enabled = false)來忽略測試方法。

創建一個Maven項目,其結構如下所示 -

TestNG忽略測試

pom.xml 依懶包配置 -

<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>com.yiibai</groupId>
    <artifactId>IgnoreTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>IgnoreTest</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.8.7</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

創建一個測試類:TestIgnore.java,其代碼如下所示 -

package com.yiibai;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestIgnore {

    @Test // default enable=true
    public void test1() {
        Assert.assertEquals(true, true);
    }

    @Test(enabled = true)
    public void test2() {
        Assert.assertEquals(true, true);
    }

    @Test(enabled = false)
    public void test3() {
        Assert.assertEquals(true, true);
    }

}

運行上面代碼,得到以下結果 -

[TestNG] Running:
  C:\Users\Administrator\AppData\Local\Temp\testng-eclipse-834820920\testng-customsuite.xml

PASSED: test1
PASSED: test2

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by org.testng.reporters.XMLReporter@1b40d5f0: 12 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@6ea6d14e: 33 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@4563e9ab: 4 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@2aaf7cc2: 42 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@45c8e616: 4 ms