如何根据条件禁用 TestNG 测试

发布于 2024-09-27 20:20:21 字数 355 浏览 1 评论 0原文

目前有没有一种方法可以根据条件禁用 TestNG 测试

我知道您当前可以在 TestNG 中禁用测试:

@Test(enabled=false, group={"blah"})
public void testCurrency(){
...
}

我想根据条件禁用相同的测试,但不知道如何操作。像这样的事情:

@Test(enabled={isUk() ? false : true), group={"blah"})
public void testCurrency(){
...
}

任何人都知道这是否可能。

Is there currently a way to disable TestNG test based on a condition

I know you can currently disable test as so in TestNG:

@Test(enabled=false, group={"blah"})
public void testCurrency(){
...
}

I will like to disable the same test based on a condition but dont know how. something Like this:

@Test(enabled={isUk() ? false : true), group={"blah"})
public void testCurrency(){
...
}

Anyone has a clue on whether this is possible or not.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

在用 @BeforeMethod 注释的方法中抛出 SkipException 对我来说不起作用,因为它跳过了我的测试套件的所有剩余测试,而不考虑 SkipException< /code> 被抛出用于这些测试。

我没有彻底调查它,但我找到了另一种方法:在 @Test 注释上使用 dependsOnMethods 属性:

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

public class MyTest {

  private boolean conditionX = true;
  private boolean conditionY = false;

  @Test
  public void isConditionX(){
    if(!conditionX){
      throw new SkipException("skipped because of X is false");
    }
  }

  @Test
  public void isConditionY(){
    if(!conditionY){
      throw new SkipException("skipped because of Y is false");
    }
  }

  @Test(dependsOnMethods="isConditionX")
  public void test1(){

  }

  @Test(dependsOnMethods="isConditionY")
  public void test2(){

  }
}

Throwing a SkipException in a method annotated with @BeforeMethod did not work for me because it skipped all the remaining tests of my test suite with no regards if a SkipException were thrown for those tests.

I did not investigate it thoroughly but I found another way : using the dependsOnMethods attribute on the @Test annotation:

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

public class MyTest {

  private boolean conditionX = true;
  private boolean conditionY = false;

  @Test
  public void isConditionX(){
    if(!conditionX){
      throw new SkipException("skipped because of X is false");
    }
  }

  @Test
  public void isConditionY(){
    if(!conditionY){
      throw new SkipException("skipped because of Y is false");
    }
  }

  @Test(dependsOnMethods="isConditionX")
  public void test1(){

  }

  @Test(dependsOnMethods="isConditionY")
  public void test2(){

  }
}
羁拥 2024-10-04 20:20:22

SkipException:当类中只有一个 @Test 方法时,它很有用。与数据驱动框架一样,我只有一个测试方法,需要根据某些条件执行或跳过。因此,我将检查条件的逻辑放入 @Test 方法中并获得所需的结果。
它帮助我获得了测试用例结果为“通过/失败”和特定“跳过”的范围报告。

SkipException: It's useful in case of we have only one @Test method in the class. Like for Data Driven Framework, I have only one Test method which need to either executed or skipped on the basis of some condition. Hence I've put the logic for checking the condition inside the @Test method and get desired result.
It helped me to get the Extent Report with test case result as Pass/Fail and particular Skip as well.

失眠症患者 2024-10-04 20:20:21

一个更简单的选择是在检查您的条件的方法上使用 @BeforeMethod 注释。如果您想跳过测试,只需抛出 SkipException 即可。像这样:

@BeforeMethod
protected void checkEnvironment() {
  if (!resourceAvailable) {
    throw new SkipException("Skipping tests because resource was not available.");
  }
}

An easier option is to use the @BeforeMethod annotation on a method which checks your condition. If you want to skip the tests, then just throw a SkipException. Like this:

@BeforeMethod
protected void checkEnvironment() {
  if (!resourceAvailable) {
    throw new SkipException("Skipping tests because resource was not available.");
  }
}
失与倦" 2024-10-04 20:20:21

您有两个选择:

您的注释转换器将测试条件,然后覆盖 @Test 注释以在不满足条件时添加属性“enabled=false”。

You have two options:

Your annotation transformer would test the condition and then override the @Test annotation to add the attribute "enabled=false" if the condition is not satisfied.

波浪屿的海角声 2024-10-04 20:20:21

据我所知,有两种方法可以让您控制 TestNG 中的“禁用”测试。

需要特别注意的区别是,SkipException 将中断所有后续测试,同时实现 IAnnotationTransformer 使用 Reflection 来根据您指定的条件取消单个测试。我将解释 SkipException 和 IAnnotationTransfomer。

SKIP 异常示例

import org.testng.*;
import org.testng.annotations.*;

public class TestSuite
{
    // You set this however you like.
    boolean myCondition;
    
    // Execute before each test is run
    @BeforeMethod
    public void before(Method methodName){
        // check condition, note once you condition is met the rest of the tests will be skipped as well
        if(myCondition)
            throw new SkipException();
    }
    
    @Test(priority = 1)
    public void test1(){}
    
    @Test(priority = 2)
    public void test2(){}
    
    @Test(priority = 3)
    public void test3(){}
}

IAnnotationTransformer 示例

有点复杂,但其背后的想法是一个称为反射的概念。

维基 - http://en.wikipedia.org/wiki/Reflection_(computer_programming)

首先实现 IAnnotation 接口,将其保存在 *.java 文件中。

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;

public class Transformer implements IAnnotationTransformer {

    // Do not worry about calling this method as testNG calls it behind the scenes before EVERY method (or test).
    // It will disable single tests, not the entire suite like SkipException
    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod){

        // If we have chose not to run this test then disable it.
        if (disableMe()){
            annotation.setEnabled(false);
        }
    }

    // logic YOU control
    private boolean disableMe() {
    }
}

然后在测试套件 java 文件中的 @BeforeClass 函数中执行以下操作

import org.testng.*;
import org.testng.annotations.*;

/* Execute before the tests run. */    
@BeforeClass
public void before(){

    TestNG testNG = new TestNG();
    testNG.setAnnotationTransformer(new Transformer());
}

@Test(priority = 1)
public void test1(){}

@Test(priority = 2)
public void test2(){}

@Test(priority = 3)
public void test3(){}

最后一步是确保在 build.xml 文件中添加侦听器。
我的最终看起来像这样,这只是 build.xml 中的一行:

<testng classpath="${test.classpath}:${build.dir}" outputdir="${report.dir}" 
    haltonfailure="false" useDefaultListeners="true"
    listeners="org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter,Transformer" 
    classpathref="reportnglibs"></testng>

There are two ways that I know of that allow you the control of "disabling" tests in TestNG.

The differentiation that is very important to note is that SkipException will break out off all subsequent tests while implmenting IAnnotationTransformer uses Reflection to disbale individual tests, based on a condition that you specify. I will explain both SkipException and IAnnotationTransfomer.

SKIP Exception example

import org.testng.*;
import org.testng.annotations.*;

public class TestSuite
{
    // You set this however you like.
    boolean myCondition;
    
    // Execute before each test is run
    @BeforeMethod
    public void before(Method methodName){
        // check condition, note once you condition is met the rest of the tests will be skipped as well
        if(myCondition)
            throw new SkipException();
    }
    
    @Test(priority = 1)
    public void test1(){}
    
    @Test(priority = 2)
    public void test2(){}
    
    @Test(priority = 3)
    public void test3(){}
}

IAnnotationTransformer example

A bit more complicated but the idea behind it is a concept known as Reflection.

Wiki - http://en.wikipedia.org/wiki/Reflection_(computer_programming)

First implement the IAnnotation interface, save this in a *.java file.

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;

public class Transformer implements IAnnotationTransformer {

    // Do not worry about calling this method as testNG calls it behind the scenes before EVERY method (or test).
    // It will disable single tests, not the entire suite like SkipException
    public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod){

        // If we have chose not to run this test then disable it.
        if (disableMe()){
            annotation.setEnabled(false);
        }
    }

    // logic YOU control
    private boolean disableMe() {
    }
}

Then in you test suite java file do the following in the @BeforeClass function

import org.testng.*;
import org.testng.annotations.*;

/* Execute before the tests run. */    
@BeforeClass
public void before(){

    TestNG testNG = new TestNG();
    testNG.setAnnotationTransformer(new Transformer());
}

@Test(priority = 1)
public void test1(){}

@Test(priority = 2)
public void test2(){}

@Test(priority = 3)
public void test3(){}

One last step is to ensure that you add a listener in your build.xml file.
Mine ended up looking like this, this is just a single line from the build.xml:

<testng classpath="${test.classpath}:${build.dir}" outputdir="${report.dir}" 
    haltonfailure="false" useDefaultListeners="true"
    listeners="org.uncommons.reportng.HTMLReporter,org.uncommons.reportng.JUnitXMLReporter,Transformer" 
    classpathref="reportnglibs"></testng>
冷心人i 2024-10-04 20:20:21

我更喜欢这种基于注释的方式来根据环境设置禁用/跳过一些测试。易于维护,不需要任何特殊的编码技术。

  • 使用 IInvokedMethodListener 接口
  • 创建自定义注释,例如: @SkipInHeadlessMode
  • 抛出 SkipException
public class ConditionalSkipTestAnalyzer implements IInvokedMethodListener {
    protected static PropertiesHandler properties = new PropertiesHandler();

    @Override
    public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult result) {
        Method method = result.getMethod().getConstructorOrMethod().getMethod();
        if (method == null) {
            return;
        }
        if (method.isAnnotationPresent(SkipInHeadlessMode.class)
                && properties.isHeadlessMode()) {
            throw new SkipException("These Tests shouldn't be run in HEADLESS mode!");
        }
    }

    @Override
    public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
        //Auto generated
    }
}

检查详细信息:
https://www.lenar.io/skip-testng -tests-based-condition-using-iinvokedmethodlistener/

I prefer this annotation based way for disable/skip some tests based on environment settings. Easy to maintain and not requires any special coding technique.

  • Using the IInvokedMethodListener interface
  • Create a custom anntotation e.g.: @SkipInHeadlessMode
  • Throw SkipException
public class ConditionalSkipTestAnalyzer implements IInvokedMethodListener {
    protected static PropertiesHandler properties = new PropertiesHandler();

    @Override
    public void beforeInvocation(IInvokedMethod invokedMethod, ITestResult result) {
        Method method = result.getMethod().getConstructorOrMethod().getMethod();
        if (method == null) {
            return;
        }
        if (method.isAnnotationPresent(SkipInHeadlessMode.class)
                && properties.isHeadlessMode()) {
            throw new SkipException("These Tests shouldn't be run in HEADLESS mode!");
        }
    }

    @Override
    public void afterInvocation(IInvokedMethod iInvokedMethod, ITestResult iTestResult) {
        //Auto generated
    }
}

Check for the details:
https://www.lenar.io/skip-testng-tests-based-condition-using-iinvokedmethodlistener/

雅心素梦 2024-10-04 20:20:21

第三选项也可以是假设
TestNG 的假设 - 当假设失败时,TestNG 将被指示忽略测试用例,因此不会执行它。

  • 使用 @Asuction 注释
  • 使用 AsductionListener 使用 Assumes.assumeThat(...)
    方法

您可以使用以下示例: 在 TestNG 中有条件地运行测试

A Third option also can be Assumption
Assumptions for TestNG - When a assumption fails, TestNG will be instructed to ignore the test case and will thus not execute it.

  • Using the @Assumption annotation
  • Using AssumptionListener Using the Assumes.assumeThat(...)
    method

You can use this example: Conditionally Running Tests In TestNG

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文