如何在 TestNG 中忽略一個類?


TestNG 支援多種方法來忽略所有 @Test 的執行。根據需求,使用者可以忽略整個測試而無需執行。

TestNG 支援以下級別來忽略所有 @Test:

  • 在一個類中

  • 在一個特定的包中

  • 在一個包及其所有子包中

使用者必須在所需級別使用 @Ignore 註解來停用測試。@Ignore 註解的優先順序高於單個 @Test 註解。

要停用類中的所有 @Test,只需在類名前寫 @Ignore。這將停用類中存在的所有 @Test。

在本文中,我們將說明如何在類中停用整個測試。

解決此問題的方法/演算法

  • 步驟 1:建立一個 TestNG 類 - NewTestngClass。

  • 步驟 2:在 NewTestngClass 類中編寫 2 個不同的 @Test 方法,並在類名前放置 @Ignore 註解,如程式設計程式碼部分所示。

  • 步驟 3:現在建立如下所示的 testng.xml 來執行 TestNG 類。

  • 步驟 4:現在,執行 testng.xml 或直接在 IDE 中執行 TestNG 類,或者使用命令列編譯並執行它。

示例

以下程式碼是常用的 TestNG 類 - NewTestngClass

src/ NewTestngClass.java

import org.testng.SkipException;
import org.testng.annotations.Test;

@Ignore
public class NewTestngClass {

    @Test(enabled=false)
    public void testcase1(){
        System.out.println("Testcase 1 - Not executed");
    }
    @Test
    public void testcase2(){
        System.out.println("Testcase 2 - skip exception example");
        throw new SkipException("Skipping this exception");
    }

    @Test
    public void testcase3(){
        boolean DataAvailable=false;
        System.out.println("Test Case3 - Conditional Skip");
        if(!DataAvailable)
            throw new SkipException("Skipping this exception");
        System.out.println("Executed Successfully");
    }

} 

testng.xml

這是一個配置檔案,用於組織和執行 TestNG 測試用例。

當只需要執行有限的測試而不是完整的套件時,它非常方便。

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name = "Suite1">
   <test name = "test1">
      <classes>
    <class name = "NewTestngClass"/>
      </classes>
   </test>
</suite>

輸出

===============================================
Suite1
Total tests run: 0, Passes: 0, Failures: 0, Skips: 0
===============================================

更新於:2023-08-17

578 次檢視

啟動您的 職業生涯

完成課程後獲得認證

開始學習
廣告