1 package test.listeners; 2 3 import org.testng.Assert; 4 import org.testng.IExecutionListener; 5 import org.testng.TestNG; 6 import org.testng.annotations.Test; 7 import org.testng.xml.XmlSuite; 8 import org.testng.xml.XmlTest; 9 10 import test.SimpleBaseTest; 11 12 import java.util.Arrays; 13 14 public class ExecutionListenerTest extends SimpleBaseTest { 15 16 public static class ExecutionListener implements IExecutionListener { 17 public static boolean m_start = false; 18 public static boolean m_finish = false; 19 20 @Override onExecutionStart()21 public void onExecutionStart() { 22 m_start = true; 23 } 24 25 @Override onExecutionFinish()26 public void onExecutionFinish() { 27 m_finish = true; 28 } 29 } 30 31 @Test executionListenerWithXml()32 public void executionListenerWithXml() { 33 runTest(ExecutionListener1SampleTest.class, true /* add listener */, true /* should run */); 34 } 35 36 @Test executionListenerWithoutListener()37 public void executionListenerWithoutListener() { 38 runTest(ExecutionListener1SampleTest.class, false /* don't add listener */, 39 false /* should not run */); 40 } 41 42 @Test executionListenerAnnotation()43 public void executionListenerAnnotation() { 44 runTest(ExecutionListener2SampleTest.class, false /* don't add listener */, 45 true /* should run */); 46 } 47 runTest(Class<?> listenerClass, boolean addListener, boolean expected)48 private void runTest(Class<?> listenerClass, boolean addListener, boolean expected) { 49 XmlSuite s = createXmlSuite("ExecutionListener"); 50 XmlTest t = createXmlTest(s, "Test", listenerClass.getName()); 51 52 if (addListener) { 53 s.addListener(ExecutionListener.class.getName()); 54 } 55 TestNG tng = create(); 56 tng.setXmlSuites(Arrays.asList(s)); 57 ExecutionListener.m_start = false; 58 ExecutionListener.m_finish = false; 59 tng.run(); 60 61 Assert.assertEquals(ExecutionListener.m_start, expected); 62 Assert.assertEquals(ExecutionListener.m_finish, expected); 63 } 64 } 65