Junit : Runlistener overriden method (testFinished) not called when running a Parameterized test

1.7k views Asked by At

I have a requirement to run a parameterized test which is working fine as expected , but the concern here is , In our framework we have our own custom listener class which extends RunListener and overrides all methods . but none of the methods is overriden when i run the test as a parameterized test . but the same works fine if i run a test without a parameters .

below is my CustomJunitListener

{
/**
 * Class used to do some report regarding the JUnit event notifier
 */
public class CustomJUnitListener extends RunListener {

  SeleniumTest test = null;

  public void setSeleniumTest(SeleniumTest test) {
    this.test = test;
  }

  /** {@inheritDoc} */
  @Override
  public void testFinished(Description description) throws Exception {
    if (test != null) {
      test.postExecution();
    }
  }



}

the method postExection is not called when i run a paramterized test . I want postExection method to be called after completion of each set of parameters for a test.

Below is my selenium test

@RunWith(Parameterized.class)
public class Test_Script extends SeleniumTest{

  private String testName;
  private String from;
  private String to;

  public Test_Script(String testName , String from, String to) {
    this.testName =testName;
    this.from =from;
    this.to =to;
  }

  @Test
  public void scenario()throws Exception{
     /* Test Script */
  }

  @Parameters
  public static Collection<Object[]> getData() throws ParserConfigurationException, SAXException, IOException {
    XMLReader reader = new XMLReader("NewFile.xml");
    return reader.readXML();
  }

Please provide me your inputs on this .

1

There are 1 answers

1
Matthew Farwell On BEST ANSWER

This isn't the way to use a RunListener. RunListener is independent from the test - you add it to the class that is running your test (in your case the Parameterized class), not your test itself. For an example of how to use RunListener, see How to add listener in Junit testcases.

However, I suspect this isn't actually what you want. You probably want to look at TestRules, specifically the ExternalResource class. This allows you to define a before() and after() method that you can reuse more easily:

@Rule ExternalResource myRule = new ExternalResource() {
    public void after() {
        test.postExecution();
    }
}

For more information, see JUnit wiki - Rules