简体   繁体   English

TestNg,注释“ beforeTestMethod”并覆盖

[英]TestNg, annotation “beforeTestMethod” and override

For my tests I'm using a base class MyTestBase defining a method setup() that does some base preparations: 对于我的测试,我使用基类MyTestBase定义了执行一些基础准备工作的方法setup()

public class MyTestBase {
    @Configuration( beforeTestMethod=true )
    protected void setup() {
        // do base preparations
    }
}

Now I have some more specific test classes that have to do their own preparations. 现在,我有一些更具体的测试类,它们必须做自己的准备。 There are different ways how to implement this. 有多种实现方法。

I could use @Override : 我可以使用@Override

public class MySpecialTestBase extends MyTestBase {
    @Override
    protected void setup() {
        super.setup();
        // do additional preparations
    }
}

...or I could use a separate setup method: ...或者我可以使用单独的设置方法:

public class MySpecialTestBase extends MyTestBase {
    @Configuration( beforeTestMethod=true )
    protected void setupSpecial() {
        // do additional preparations
    }
}

Is there a prefered way to implement this? 是否有实现此目的的首选方法?

I would prefer using @Configuration annotation. 我更喜欢使用@Configuration批注。 @Override and super are more fragile. @Overridesuper更脆弱。 You can forget to call super.setup() , or call it in wrong place. 您可以忘记调用super.setup()或在错误的地方调用它。 Meanwhile, using separate method with @Configuration lets you to choose more appropriate naming for child setup method if necessary, and you get setup order guaranteed by TestNG (parent then child). 同时,将单独的方法与@Configuration可让您在必要时为子设置方法选择更合适的命名,并获得TestNG保证的设置顺序(父先子)。

Two more points: 还有两点:

  1. I'd make parent setup final in order to forbid accidental overriding. 为了避免意外覆盖,我将使父设置final
  2. I'd use @BeforeMethod annotations. 我会使用@BeforeMethod批注。 They are available since TestNG 5.0. 从TestNG 5.0开始可用。 Of course, for older versions you forced to using @Configuration . 当然,对于旧版本,您不得不使用@Configuration

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM