TestNG. BeforeMethod groups

Ok, what is the “TestNG BeforeMethod groups” issue about?

For example you have several tests in your TestNG test class. Some of them belong to the “stage” group others to “prod” and you annotated them with @Test(groups = {"stage"}) and @Test(groups = {"prod"}).
Also you want to do some setup steps and add the setup method annotated with @BeforeMethod.

public class BeforMethodAndGroupsTest {
	
	@BeforMethod
	public void setUp() {
		// Preparing the world for the test
	}

	@Test(groups = {"stage"})
	public void stageSpecificTest() {
		// Very important stage tests
	}

	@Test(groups = {"prod"})
	public void prodSpecificTest() {
		// Very important prod tests
	}

}

Everything works fine while you run them all but once you run the tests that belong the specific group/groups you will see your @BeforeMethod is never run.

Here is how to fix that - just set alwaysRun parameter of the @BeforeMethod annotation to true

@TestMethod(alwaysRun = true)

The final code that fixes the “TestNG BeforeMethod groups” issue:

public class BeforMethodAndGroupsTest {
	
	@BeforMethod(alwaysRun = true)
	public void setUp() {
		// Preparing the world for the test
	}

	@Test(groups = {"stage"})
	public void stageSpecificTest() {
		// Very important "stage" test
	}

	@Test(groups = {"prod"})
	public void prodSpecificTest() {
		// Very important "prod" test
	}

}

Looks so obvious but you can’t imagine how often I spent a lot of time to figure out why I got NPE (Null Pointer Exception) in my test.

Note: Highly recommend not to use different setups for different groups in one class - you will not notice how quickly it will turn into a pain in the ass. For these cases let different group tests live in different classes.


You may also find these posts interesting: