【问题标题】:Common annotations used in different test classes不同测试类中使用的常用注解
【发布时间】:2021-09-14 19:29:46
【问题描述】:

我对@9​​87654321@ 或@BeforeMethod 等注释有疑问。是否可以设置全局注释,以便我所有的测试类都将使用它们?我的框架中有超过 20 个测试类和很多测试方法。每个测试类都有@BeforeTest@BeforeMethod 之类的先决条件,但是对于每个测试类,这些先决条件是相同的。所以我认为这可能是一个好主意,编写一个通用的注解方法,可以在每个测试类中使用。

【问题讨论】:

  • 使用监听器。
  • @BoristheSpider 怎么用?你能解释一下吗?

标签: java annotations testng testng-annotation-test


【解决方案1】:

使用继承使代码可重用。创建超类DefaultTestCase

public class DefaultTestCase{
  @BeforeTest
  public void beforeTest() {
     System.out.println("beforeTest");
  }  
  @BeforeMethod
  public void beforeMethod() {
    System.out.println("beforeMethod");
  }  
}

每个测试用例类都扩展DefaultTestCase:

public class ATest extends DefaultTestCase{
  @Test
  public void test() {
     System.out.println("test");
  }
  @Test
  public void anotherTest() {
     System.out.println("anotherTest");
  }
}

输出:

beforeTest
beforeMethod
test
beforeMethod
anotherTest

【讨论】:

    【解决方案2】:

    使用ITestListenerIClassListener 的实现,您可以执行以下操作。 onTestStart 将在每个测试用例之前调用,onStart 将在您的套件中为 <test> 调用,onBeforeClass 对每个类执行一次。

    public class MyListener implements ITestListener, IClassListener {
        
        @Override
        public void onStart(ITestContext context) {
            // Put the code in before test.
            beforeTestLogic();
        }
    
        @Override
        public void onBeforeClass(ITestClass testClass) {
            // Put the code in before class.
            beforeClassLogic();
        }
    
        @Override
        public void onTestStart(ITestResult result) {
            // Put the code in before method.
            beforeMethodLogic();
        }
    }
    

    现在将@Listener 注解添加到所需的测试类中:

    @Test
    @Listener(MyListener.class)
    public class MyTest {
        // ........
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 2017-10-25
      • 2019-09-15
      • 1970-01-01
      • 2012-01-19
      • 2017-12-12
      • 2021-03-14
      • 2011-07-26
      • 2019-10-20
      相关资源
      最近更新 更多