Home » Enterprise Java » TestNG » TestNG beforeMethod Example

About Ram Mokkapaty

Ram Mokkapaty
Ram holds a master's degree in Machine Design from IT B.H.U. His expertise lies in test driven development and re-factoring. He is passionate about open source technologies and actively blogs on various java and open-source technologies like spring. He works as a principal Engineer in the logistics domain.

TestNG beforeMethod Example

In this article, I will show you an example of TestNG @BeforeMethod. This is one of the annotations provided by TestNG that gets invoked before the execution of each test method.

It is very similar to JUnit’s setUp() and is useful if you want to setup some test data before the start of the test method.

But first my setup details:

  • I am using Eclipse as the IDE, version Luna 4.4.1.
  • I will be running the tests using eclipse TestNG plugin so you need to install TestNG Eclipse Plugin.

1. Multiple @BeforeMethod methods with variations

In this example, I have three variations of @BeforeMethod. First beforeMethod is a straightforward one with no-parameters. The second one staticBeforeMethod is a static @BeforeMethod method and the last one beforeMethodWithParam receives a String parameter as an argument. The TestClass also contains other methods like @BeforeTest, @BeforeClass and the @After versions. It also contains two test methods unitLevel1 and unitLevel2.

We will be running the example through a test configuration testng.xml so we will include the test class in it. Since one of the @BeforeMethod has a parameter, we need to specify the parameter and its value in the configuration file. We will add a parameter element with attribute name set to param and attribute value set to 'I am beforeMethod'

testng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Feature" parallel="false">
  <test name="UnitLevelTest">
    <classes>
      <parameter name="param" value="'I am beforeMethod'"/>
      <class name="com.javacodegeeks.testng.TestClass"/>      
    </classes>
  </test>
</suite>

Each method prints a simple message so we know the order in which the methods are invoked.

TestClass:

package com.javacodegeeks.testng;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class TestClass {

	@BeforeTest
	public void beforeTest() {
		System.out.println("testClass: before test");
	}

	@Test
	public void unitLevel1() {
		System.out.println("testClass: Unit level1 testing");
	}

	@Test
	public void unitLevel2() {
		System.out.println("testClass: Unit level2 testing");
	}

	@BeforeMethod
	public void beforeMethod() {
		System.out.println("testClass: before method");
	}

	@BeforeMethod
	public static void staticBeforeMethod() {
		System.out.println("testClass: static before method");
	}

	@Parameters({ "param" })
	@BeforeMethod
	public void beforeMethodWithParam(String p) {
		System.out.println("testClass: before method with param " + p);
	}

	@AfterMethod
	public void afterMethod() {
		System.out.println("testClass: after method");
	}

	@BeforeClass
	public void beforeClass() {
		System.out.println("testClass: before class");
	}

	@AfterClass
	public void afterClass() {
		System.out.println("testClass: after class");
	}

	@AfterTest
	public void afterTest() {
		System.out.println("testClass: after test");
	}
}

You can see in the output that the @BeforeMethod methods fire once for each test method.

Output:

[TestNG] Running:
  C:\javacodegeeks_ws\testNgBeforeMethod\test\com\javacodegeeks\testng\testng.xml

testClass: before test
testClass: before class
testClass: before method with param 'I am beforeMethod'
testClass: before method
testClass: static before method
testClass: Unit level1 testing
testClass: after method
testClass: before method with param 'I am beforeMethod'
testClass: before method
testClass: static before method
testClass: Unit level2 testing
testClass: after method
testClass: after class
testClass: after test

===============================================
Feature
Total tests run: 2, Failures: 0, Skips: 0
===============================================

2. Private @BeforeMethod

In this example, I have a private @BeforeMethod but irrespective of its access modifier it always gets invoked before the @Test method executes.

privateBeforeMethodTestng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Feature" parallel="false">
  <test name="UnitLevelTest">
    <classes>
      <class name="com.javacodegeeks.testng.BeforeMethodPrivateExample"/>      
    </classes>
  </test>
</suite>

The test class has one private @BeforeMethod called privateBeforeMethod and another public method called disabledBeforeMethod which is also @BeforeMethod but disabled.

BeforeMethodPrivateExample:

package com.javacodegeeks.testng;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class BeforeMethodPrivateExample {
	@BeforeMethod
	private void privateBeforeMethod() {
		System.out.println("private beforeMethod called");
	}

	@BeforeMethod(enabled = false)
	public void disabledBeforeMethod() {
		System.out.println("this method is not enabled, this should not get called");
	}

	@Test
	public void dummyTest() {
		System.out.println("Dummy test");
	}
}

The private @BeforeMethod is called but not the one which is disabled.

Output:

[TestNG] Running:
  C:\javacodegeeks_ws\testNgBeforeMethod\test\com\javacodegeeks\testng\privateBeforeMethodTestng.xml

private beforeMethod called
Dummy test

===============================================
Feature
Total tests run: 1, Failures: 0, Skips: 0
===============================================

3. @BeforeMethod with parameters

A @BeforeMethod method can be declared with a parameter of type ITestContext or type java.lang.reflect.Method. This parameter will receive the test method that will be called once the @BeforeMethod finishes.

A @BeforeMethod can also be declared with a parameter of type Object[]. The data will be injected using the @DataProvider that the test method is configured with.

beforeMethodsParamTestng.xml:

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Feature" parallel="false">
  <test name="UnitLevelTest">
    <classes>
      <class name="com.javacodegeeks.testng.BeforeMethodParametersExample"/>      
    </classes>
  </test>
</suite>

The test class has a couple of @BeforeMethod methods and a couple of test methods. We also have two @DataProvider methods. Each test method is configured with one @DataProvider. The @BeforeMethod method that receives Method and ITestContext, prints the method name and suite name. The other @BeforeMethod method that receives Object[] data, prints the data.

BeforeMethodParametersExample:

package com.javacodegeeks.testng;

import java.lang.reflect.Method;

import org.testng.ITestContext;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class BeforeMethodParametersExample {
	private Method method;
	private ITestContext context;
	private static final Object[][] DATA1 = { new Object[] { "first" },
			new Object[] { "second" }, };
	private static final Object[][] DATA2 = { new Object[] { "1" },
		new Object[] { "2" }, };

	@BeforeMethod
	public void before(Method m, ITestContext ctx) {
		method = m;
		context = ctx;
	}
	
	@BeforeMethod
	public void beforeWithData(Object[] data) {
		for (Object o : data) {
			System.out.println("Data " + o);
		}
	}

	@Test(dataProvider="data1")
	public void someTest(String data) {
		System.out.println("Name of test is " + method.getName());
		System.out.println("Suite name is " + context.getSuite().getName());
	}
	
	@Test(dataProvider="data2")
	public void dummyTest(String data) {
		System.out.println("dummyTest: " + data);
	}
	
	@DataProvider
	public Object[][] data1() {
		return DATA1;
	}	
	
	@DataProvider
	public Object[][] data2() {
		return DATA2;
	}	
}

You can see from the output that the @BeforeMethod gets called for each data set that @DataProvider returns.

Output:

[TestNG] Running:
  C:\javacodegeeks_ws\testNgBeforeMethod\test\com\javacodegeeks\testng\beforeMethodParamsTestng.xml

Data 1
dummyTest: 1
Data 2
dummyTest: 2
Data first
Name of test is someTest
Suite name is Feature
Data second
Name of test is someTest
Suite name is Feature

===============================================
Feature
Total tests run: 4, Failures: 0, Skips: 0
===============================================

Download the Eclipse Project

In this article I have shown you several examples of TestNG @BeforeMethod.

Download
You can download the full source code of this example here: testNgBeforeMethod.zip
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of