Advanced TestNG Tutorials 33: Integration and Usage of BeanShell In TestNG XML

Hello Folks,

We have learnt how can we customise testng xml to run test methods belonging to multiple groups.

Let’s consider a new scenario:

Suppose There are three methods M1 ( belongs to group WIndows), M2(belongs to group Windows and Linux) and M3(belongs to group Windows ,Linux and Mac). You want to run methods which belong to both “WIndows” and “Linux” together i.e. M2.

You can not do such setting in testng xml using include or exclude tags. Here you need “AND” & “OR” logics. To achieve this we need “BeanShell” scripting.

Introduction of BeanShell:

As per doc:

BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell executes standard Java statements and expressions but also extends Java into the scripting domain with common scripting language conventions and syntax. BeanShell is a natural scripting language for Java.

It comes builtin with TestNG jar.

I will not explain about beanShell much here. But you can always refer its doc. I will explain how you can achieve solution of above scenario.

Since beanshell comes inbuilt with TestNG jar, so you don’t require it to add. You need to include beanshell scripts with <script> tag as we do normally to embed javascript code with html.

Let’s create a testng class first as below:

Now you are required to run test method which belong to “Window” and “Linux” together i.e method “MethodsBelongToG1G2”. If you use traditional include and exclude tag, you can not achieve this. You need to achieve “AND” condition with group names. To achieve this you need to write beanshell script.

Update testng xml as below:

I added comments for your understanding. RUn it as testng suite and you will see only desired method is run.


Even you can write java codes like print statements and it will work perfectly fine.

Hope you learnt something new.

More about TestNG in upcoming posts. Stay tuned.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.