How to Use Beanshell Script in TestNG?


TestNG supports to group the test cases based on similar functionality or uses.

Sometimes user has customized conditions to pick classes/methods/groups at run time based on conditions and use cases. TestNG supports simple frequently use scenarios but covering all expects are unnecessary. For Example, user may add multiple groups to single test. While running the group using <groups><run><include> syntax, TestNG runs all tests those are part of the group. It works as OR statement. Like if a test has 2 groups and only 1 is mentioned in <include> tag it will run the test.

But, when user wants to run a test only if all the groups are mentioned i.e. AND statement. TestNG doesn’t support directly AND statements in groups. For Example: @Test ( groups = {“unit”, “integration”} )

If user wants to run this test only if group is mentioned as unit and integration not either unit or integration.

This functionality can be supported by Beanshell. It provides the user to scripting facility to put customized conditions in testng.xml based on need. User can add any conditions as scripts to fetch the required tests/methods/classes/groups or anything else.

In this tutorial, we will illustrate how to implement Beanshell in testng.xml to achieve customized conditions. Example is taken for multiple groups condition.

Approach/Algorithm to solve this problem

  • Step 1: Create a TestNG classes − NewTestngClass

  • Step 2: Write 3 @Test method in all the classes with 2 as single group while one is having 2 groups.

  • Step 3: Now create the testNG.xml as given below with Beanshell scripting.

  • Step 4: If you are running testng.xml alone (not with maven), make sure Beanshell jar is downloaded and configured properly.

  • Step 5: If you are running testng.xml as part of maven build, please add beanshell dependency in pom.xml

  • Step 6: Now, run the testNG.xml directly or using mvn command.

Example

The following code to show how to run only test group based on customized condition:

src/ NewTestngClass.java

import org.testng.annotations.Test;

public class NewTestngClass {

    @Test(groups = { "unit", "integration" })
    public void testCase1() {
        System.out.println("in test case 1 of NewTestngClass");
    }
    @Test(groups = { "integration" })
    public void testCase2() {
        System.out.println("in test case 2 of NewTestngClass");
    }
    @Test(groups = { "unit" })
    public void testCase3() {
        System.out.println("in test case 3 of NewTestngClass");

    }
}  

testng.xml

This is a configuration file that is used to organize and run the TestNG test cases.

It is very handy when limited tests are needed to execute rather than full suite.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="suite" parallel="none" verbose="5">
    <test name="test">
        <method-selectors>
            <method-selector>
                <script language="beanshell"><![CDATA[
       return groups.containsKey("unit") && groups.containsKey("integration");
     ]]></script>
            </method-selector>
        </method-selectors>
        <classes>
            <class name="NewTestngClass"/>
        </classes>
    </test>
</suite>

pom.xml

This is a maven configuration file that is used to organize dependencies, plugins and run the TestNG test cases.

It is very handy when limited tests are needed to execute rather than full suite.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sample</groupId>
    <artifactId>TestNGProjectct</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M5</version>
                <configuration>
                                        <suiteXmlFiles>
                                            <suiteXmlFile>src/main/java/testng.xml</suiteXmlFile>
                                        </suiteXmlFiles>

                </configuration>

            </plugin>
        </plugins>
    </build>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>

    </properties>
    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.3.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache-extras.beanshell</groupId>
            <artifactId>bsh</artifactId>
            <version>2.0b6</version>
        </dependency>


    </dependencies>
</project>

Output

[INFO] ---------------------< com.sample:TestNGProjectct >---------------------
[INFO] Building TestNGProjectct 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ TestNGProjectct ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ TestNGProjectct ---
[INFO] Nothing to compile - all classes are up to date
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ TestNGProjectct ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ TestNGProjectct ---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding UTF-8, i.e. build is platform dependent!
[INFO] Compiling 3 source files to C:\Users\anandas\IdeaProjects\TestNGProjectct\target\test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:3.0.0-M5:test (default-test) @ TestNGProjectct ---
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running TestSuite
...
... TestNG 7.3.0 by Cédric Beust (cedric@beust.com)
...

in test case 1 of NewTestngClass
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.625 s - in TestSuite
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] --------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] --------------------------------------------------------
[INFO] Total time:  3.222 s
[INFO] Finished at: 2022-02-16T11:27:08+05:30
[INFO] --------------------------------------------------------

Updated on: 16-Aug-2023

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements