TestNG – Advanced Groups Selection using BeanShell

24 September, 2014
TestNG has only the functionality to run tests depending on what groups you include or exclude in the .xml testNG suite file.

If you want to run only tests that are present in two or more groups (intersection of groups) you’ll have to use the beanshell functionality that TestNG supports in the test suite .xml file.


The TestNG default including and excluding groups functionality:
 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="my test suite" parallel="false">

    <test name="all tests" preserve-order="true">
    <groups>
      <define name="all">
        <include name="group1"/>
        <include name="group2"/>
      </define>

      <run>
        <include name="all" />
        <exclude name="group3" />
      </run>
    </groups>

    <classes>
     <class name="com.tests.MyTest" />
    </classes>

</test>


Lets say that you have a test file that is part of more groups, for example:

 
@Test(groups = {"group1","group2","group3"})
public void myTest(){
   ...
}
In order to run tests that are part of an intersection of groups you must use the TestNG BeanShell functionality.
Here you can find some details in the TestNG Documentation – Advanced Groups Selection section from http://testng.org/doc/documentation-main.html#beanshell.

In order to use Maven and pass parameters you can modify the suite file to look something like:

 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="my test suite" parallel="false">
	<test name="my tests" preserve-order="true">
		<method-selectors>
			<method-selector>
				<script language="beanshell"><![CDATA[
				runTest = false;
				groupIn = System.getProperty("includeGroups");
				groupNotIn = System.getProperty("excludeGroups");

				if ((groupIn == null) || (groupIn == "")) {
				runTest = false;
				} else {
				StringTokenizer groupsTagList = new StringTokenizer(groupIn, ",");
				runTest = true;

				while (groupsTagList.hasMoreTokens()) {
				if (!(groups.containsKey(groupsTagList.nextToken())))
				runTest = false;
				}

				if (runTest && (groupNotIn != null) && (groupNotIn != "")) {
				StringTokenizer groupsNotInList = new StringTokenizer(groupNotIn, ",");

				while (groupsNotInList.hasMoreTokens()) {
				if ((groups.containsKey(groupsNotInList.nextToken())))
				runTest = false;
				}
				}
				}
				return runTest;
				]]>
				</script>
			</method-selector>
		</method-selectors>

		<classes>
			<class name="com.tests.MyTest" />
		</classes>

</test>
</suite>
The Maven command to run you specific test that is part of the two groups is the following:
 mvn clean test -DincludeGroups=group1,group2  

No comments:

Post a Comment