【问题标题】:Junit : Runlistener overriden method (testFinished) not called when running a Parameterized testJunit:运行参数化测试时未调用 Runlistener 覆盖方法(testFinished)
【发布时间】:2013-12-16 06:51:55
【问题描述】:

我需要运行一个参数化测试,它可以按预期正常工作,但这里需要关注的是,在我们的框架中,我们有自己的自定义侦听器类,它扩展了 RunListener 并覆盖了所有方法。但是当我将测试作为参数化测试运行时,没有任何方法被覆盖。但如果我在没有参数的情况下运行测试,同样可以正常工作。

下面是我的 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();
    }
  }



}

当我运行参数化测试时,不会调用 postExection 方法。我希望在完成测试的每组参数后调用 postExection 方法。

下面是我的硒测试

@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();
  }

请提供您对此的意见。

【问题讨论】:

    标签: java junit4 parameterized


    【解决方案1】:

    这不是使用 RunListener 的方式。 RunListener 独立于测试 - 您将其添加到运行测试的类(在您的情况下为 Parameterized 类),而不是您的测试本身。有关如何使用 RunListener 的示例,请参阅How to add listener in Junit testcases

    但是,我怀疑这实际上不是您想要的。您可能想查看 TestRules,特别是 ExternalResource 类。这允许您定义一个更容易重用的 before() 和 after() 方法:

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

    更多信息请见JUnit wiki - Rules

    【讨论】:

    • 首先非常感谢您的投入,我非常感谢您的即时回复,它解决了我的问题。同样正如你所说,我们的 Runlistener 独立于测试,我只是在我的评论中发布了更好的理解
    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多