04
Sep

Service Loader example with TestNG

Service Loader example with TestNG


ServiceLoader, is an utility class to look for implementations of interfaces found on the classpath. This is useful for TestNG classes as you need not to specify via @Listeners / testng.xml.


Steps to define Service Loader for TestNG custom Implementation

#1.  Create your custom implementation for TestNG Interface.  eg.

import org.testng.ISuite;
import org.testng.ISuiteListener;

public class TmpSuiteListener implements ISuiteListener {
	public static boolean start = false;

	public static boolean finish = false;

	@Override
	public void onFinish(ISuite arg0) {
		System.out.println("Finishing");
	}

	@Override
	public void onStart(ISuite arg0) {
		System.out.println("Starting");
	}

}


#2.  Create your TestNG tests.  eg.

import org.testng.annotations.Test;

public class ActualTest {

	@Test
	public void myFunction() {
		System.out.println("Hello..................");
	}
}


#3.  Create following folder structure under src/test/resources

|____META-INF  <Folder>
| |____services <Folder>
| | |____org.testng.ITestNGListener  <File>


#4.  Add following contents to org.testng.ITestListener file:

testNG.ServiceLoader.Example.TmpSuiteListener

Output:
=======


Starting
Hello..................
PASSED: myFunction

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

Finishing


source:  http://testng.1065351.n5.nabble.com/New-TestNG-feature-support-for-ServiceLoader-td6333.html