问题描述
对于我的测试,我使用一个基类 MyTestBase
定义一个方法 setup()
来做一些基本准备:
For my tests I'm using a base class MyTestBase
defining a method setup()
that does some base preparations:
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.
我可以使用@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
}
}
有没有更好的方法来实现这一点?
推荐答案
我更喜欢使用 @Configuration
注释.@Override
和 super
更脆弱.你可以忘记调用 super.setup()
,或者在错误的地方调用它.同时,在@Configuration
中使用单独的方法可以让您在必要时为子设置方法选择更合适的命名,并且您得到TestNG(父然后子)保证的设置顺序.
I would prefer using @Configuration
annotation. @Override
and super
are more fragile. You can forget to call super.setup()
, or call it in wrong place. 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).
另外两点:
- 我会让父级设置
final
以防止意外覆盖. - 我会使用
@BeforeMethod
注释.它们从 TestNG 5.0 开始可用.当然,对于旧版本,您不得不使用@Configuration
.
- I'd make parent setup
final
in order to forbid accidental overriding. - I'd use
@BeforeMethod
annotations. They are available since TestNG 5.0. Of course, for older versions you forced to using@Configuration
.
这篇关于TestNg,注释“beforeTestMethod";并覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!