1 package test.listeners; 2 3 import org.testng.Assert; 4 import org.testng.IAlterSuiteListener; 5 import org.testng.TestNG; 6 import org.testng.annotations.Test; 7 import org.testng.xml.XmlSuite; 8 import org.testng.xml.XmlTest; 9 import test.SimpleBaseTest; 10 11 import java.util.Arrays; 12 import java.util.List; 13 14 public class AlterSuiteListenerTest extends SimpleBaseTest { 15 16 public static final String ALTER_SUITE_LISTENER = "AlterSuiteListener"; 17 18 @Test executionListenerWithXml()19 public void executionListenerWithXml() { 20 XmlSuite suite = runTest(AlterSuiteListener1SampleTest.class, AlterSuiteNameListener.class.getName()); 21 Assert.assertEquals(suite.getName(), AlterSuiteNameListener.class.getSimpleName()); 22 } 23 24 @Test executionListenerWithoutListener()25 public void executionListenerWithoutListener() { 26 XmlSuite suite = runTest(AlterSuiteListener1SampleTest.class, null/*Donot add the listener*/); 27 Assert.assertEquals(suite.getName(), ALTER_SUITE_LISTENER); 28 } 29 30 @Test executionListenerWithXml2()31 public void executionListenerWithXml2() { 32 XmlSuite suite = runTest(AlterSuiteListener1SampleTest.class, AlterXmlTestsInSuiteListener.class.getName()); 33 Assert.assertEquals(suite.getTests().size(), 2); 34 } 35 36 runTest(Class<?> listenerClass, String listenerName)37 private XmlSuite runTest(Class<?> listenerClass, String listenerName) { 38 XmlSuite s = createXmlSuite(ALTER_SUITE_LISTENER); 39 createXmlTest(s, "Test", listenerClass.getName()); 40 boolean addListener = (listenerName != null); 41 42 if (addListener) { 43 s.addListener(listenerName); 44 } 45 TestNG tng = create(); 46 tng.setXmlSuites(Arrays.asList(s)); 47 tng.run(); 48 return s; 49 } 50 51 public static class AlterSuiteListener1SampleTest { 52 @Test foo()53 public void foo() { 54 } 55 } 56 57 58 public static class AlterSuiteNameListener implements IAlterSuiteListener { 59 60 @Override alter(List<XmlSuite> suites)61 public void alter(List<XmlSuite> suites) { 62 XmlSuite suite = suites.get(0); 63 suite.setName(getClass().getSimpleName()); 64 } 65 } 66 67 68 public static class AlterXmlTestsInSuiteListener implements IAlterSuiteListener { 69 70 @Override alter(List<XmlSuite> suites)71 public void alter(List<XmlSuite> suites) { 72 XmlSuite suite = suites.get(0); 73 List<XmlTest> tests = suite.getTests(); 74 XmlTest test = tests.get(0); 75 XmlTest anotherTest = new XmlTest(suite); 76 anotherTest.setName("foo"); 77 anotherTest.setClasses(test.getClasses()); 78 } 79 } 80 81 } 82