Java 如何根据条件禁用 TestNG 测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3945769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to disable TestNG test based on a condition
提问by Afamee
Is there currently a way to disable TestNG test based on a condition
当前是否有一种方法可以根据条件禁用 TestNG 测试
I know you can currently disable test as so in TestNG:
我知道您目前可以在 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.
任何人都知道这是否可能。
采纳答案by Cedric Beust
You have two options:
您有两个选择:
- Implement an annotation transformer.
- Use BeanShell.
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.
如果条件不满足,您的注释转换器将测试条件,然后覆盖@Test 注释以添加属性“enabled=false”。
回答by Bruce
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 注释。如果你想跳过测试,那么只需抛出一个SkipException。像这样:
@BeforeMethod
protected void checkEnvironment() {
if (!resourceAvailable) {
throw new SkipException("Skipping tests because resource was not available.");
}
}
回答by Makeen A. Sabree
There are two ways that I know of that allow you the control of "disabling" tests in TestNG.
我知道有两种方法可以让您控制 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.
需要注意的区别是,当实现 IAnnotationTransformer 时,SkipException 将中断所有后续测试,使用反射根据您指定的条件取消单个测试。我将解释 SkipException 和 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
IAnnotationTransformer 示例
A bit more complicated but the idea behind it is a concept known as Reflection.
有点复杂,但其背后的想法是一个称为反射的概念。
Wiki - http://en.wikipedia.org/wiki/Reflection_(computer_programming)
维基 - http://en.wikipedia.org/wiki/Reflection_(computer_programming)
First implement the IAnnotation interface, save this in a *.java file.
首先实现 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()){
}
Then in you test suite java file do the following in the @BeforeClass function
然后在测试套件 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(){}
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:
最后一步是确保在 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>
回答by letrait
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.
SkipException
在带有注释的方法中抛出 a@BeforeMethod
对我不起作用,因为它跳过了我的测试套件的所有剩余测试,而不考虑是否SkipException
为这些测试抛出a 。
I did not investigate it thoroughly but I found another way : using the dependsOnMethods
attribute on the @Test
annotation:
我没有彻底调查它,但我找到了另一种方法:使用注释dependsOnMethods
上的属性@Test
:
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(){
}
}
回答by avivamg
A Thirdoption 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.
一个三选项,也可以假设 假设为TestNG的-当一个假设不成立,TestNG的将被指示忽略测试用例,并因此将不会执行它。
- Using the @Assumption annotation
- Using AssumptionListener Using the Assumes.assumeThat(...) method
- 使用@Assumption 注解
- 使用 AssumptionListener 使用 Assumes.assumeThat(...) 方法
You can use this example: example
你可以使用这个例子:example
回答by PAQuality101
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.
SkipException:在类中只有一个 @Test 方法的情况下很有用。就像数据驱动框架一样,我只有一个测试方法需要根据某些条件执行或跳过。因此,我将检查条件的逻辑放在 @Test 方法中并获得所需的结果。它帮助我获得了测试用例结果为通过/失败和特定跳过的范围报告。
回答by Tóth Krisztián Gyula
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
- 使用 IInvokedMethodListener 接口
- 创建自定义注释,例如:@SkipInHeadlessMode
- 抛出跳过异常
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/
查看详情:https: //www.lenar.io/skip-testng-tests-based-condition-using-iinvokedmethodlistener/