TestNG Tutorials 27: Usage of alwaysRun Attribute With Configuration Methods of TestNG

Hello Folks,

In last post we learn usage of of alwaysRun Attribute With Test Method of TestNG. In this post, we will see usage of alwaysRun attribute with configuration method in TestNG.

What is a Configuration Method in TestNG?

When we mark a method as @BeforeXXXX or @AfterXXXX, that method is called as Configuration method. Example:

@BeforeTest
public void beforeTestMethod()
{
System.out.println(“beforeTest”);
}

Above method “beforeTestMethod” is a configuration method.

We create a TestNG class with multiple configuration methods as below:

In this TestNG class, I will explicitly fail @BeforeSuite method. Let’s see the output:

Output:

Since BeforeSuite method is failed, it skips all other configuration method and test method as well that you can see in console log above:
SKIPPED CONFIGURATION: @BeforeTest beforeTestMethod
SKIPPED CONFIGURATION: @BeforeClass beforeClassMethod
SKIPPED CONFIGURATION: @BeforeMethod beforeMethodMethod
SKIPPED CONFIGURATION: @AfterMethod afterMethodMethod
SKIPPED CONFIGURATION: @AfterClass afterClassMethod
SKIPPED CONFIGURATION: @AfterTest afterTestMethod
SKIPPED: testMethod

TestNG shows final result of suite as below:
===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 7
===============================================

You can see TestNG displays result of “Configuration” and “Test” execution separately. We have total 8 configuration methods. Out of 8, 1 failed and 7 skipped which is displayed by TestNG.

In above case, you will expect at least some configuration methods like @AfterSuite method should be run for cleanup or report generation irrespective of suite result. To achieve this, you need to use alwaysRun attribute as below:

Output:

You can see @AfterSuite annotated method gets executed as we set alwaysRun to true for it. This help you in properly wrap up suite execution.

In the same way, you can mark alwaysRun attribute to true for configuration methods which you would like to get executed in any case.

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.
#ThanksForReading
#HappySelenium

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning