Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

java - Is it possible to put a condition to TestNG to run the test if that is member of two groups?

I know you can define in your xml which groups that you want to run, but I want to know whether it is possible to say run these methods if they are both member of groups A & B.

Let's say I have the following test cases;

@Test(groups={"A","B"})
public testA() {}

@Test(groups={"B","C"})
public testB(){}

and following configuration;

<test name="Test A|B">
<groups>
       <run>
           <include name="B" />
       </run>
    </groups>

    <classes>
        <class name="com.test.Test" />
    </classes>
</test>

This will run both testA and testB since they are both members of group B. I want to run the test only if it is member of both groups A & B.

Is it possible to do such thing with TestNG?

Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create a listener implementing IMethodInterceptor interface. Which will give you an ability to access groups list from your @Test and manage your "tests to execute list" as you need. At same time ITestContext parameter allows you to access the data from testNg xml. So, you can set groups to run in default testNg manner (suite xml file); but run them depending on algorithm you implement. Something like:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.testng.IMethodInstance;
import org.testng.IMethodInterceptor;
import org.testng.ITestContext;
import org.testng.annotations.Test;

public class Interceptor implements IMethodInterceptor
{

    @Override
    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context)
    {
        int methCount = methods.size();
        List<IMethodInstance> result = new ArrayList<IMethodInstance>();

        for (int i = 0; i < methCount; i++)
        {
            IMethodInstance instns = methods.get(i);
            List<String> grps = Arrays.asList(instns.getMethod().getConstructorOrMethod().getMethod().getAnnotation(Test.class).groups());
//get these groups from testng.xml via context method parameter                         
            if (grps.contains("A") && grps.contains("B"))
            {
                result.add(instns);
            }                       
        }                       
        return result;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...