首页 > 解决方案 > 不同测试类中使用的常用注解

问题描述

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

标签: javaannotationstestngtestng-annotation-test

解决方案


使用继承使代码可重用。创建一个超类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

推荐阅读