@BeforeClass批注:Junit与TestNG [英] @BeforeClass annotation: Junit vs TestNG

查看:103
本文介绍了@BeforeClass批注:Junit与TestNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么JUnit中的@BeforeClass方法是static,而在TestNG中则是non-static? TestNG是对JUnit的改进,因此为什么他们选择这种实现方式?

Why the @BeforeClass method in JUnit is static whereas in TestNG its non-static? TestNG was developed as an improvement over JUnit, so why did they choose this way of implementation?

由于@BeforeClass仅运行一次,因此将其设置为static比将其设置为非静态更为有意义.同样在TestNG中,在哪个实例上调用@BeforeClass方法?有人可以举一个例子来更好地理解吗?

Since @BeforeClass runs only once, so making it static makes more sense than making it non static. Also in TestNG, on which instance the @BeforeClass method is called? Can someone cite an example for better understanding?

推荐答案

JUnit和TestNG之间的主要区别是测试类实例化. JUnit总是为每个测试方法运行创建测试类的新实例. TestNG仅创建一个测试类实例,然后运行该实例的所有测试方法.

The main difference between JUnit and TestNG is the test class instantiation. JUnit always creates a new instance of the test class for each test method run. TestNG only creates one test class instance and then runs all test methods of this instance.

JUnit方法保证了所有测试方法的独立性.只是没有关系,它们以什么顺序运行.此外,对于每种测试方法,所有实例字段始终设置为相同.所有测试方法通用的初始化数据必须在类级别进行,因此它必须是静态的.这就是为什么@BeforeClass方法必须是静态的原因.

The JUnit approach guarantees the independency of all test methods. It just does not matter, in which order they run. Additionally, all instance fields are always setup the same for each test method. Initializing data, that is common for all test methods, must take place at the class level, thus it must be static. This is the reason, why the @BeforeClass method must be static.

TestNG方法不能保证独立性.实际上,您不能以与JUnit测试中相同的方式使用实例字段.如果您在一种测试方法中更改了该字段,则在另一种测试方法中更改后的值仍然可见.但是,此行为也有一个优点:有时某些测试方法之间存在依赖关系.使用TestNG,测试人员可以表达它们.

The TestNG approch does not guarante the independency. In fact, you cannot use an instance field in the same manner as in JUnit tests. If you change such a field in one test method, the changed value is still observabl in another test method. However, this behavior has also an advantage: Sometimes there are dependencies between some test methods. With TestNG, a tester can express them.

由于是TestNG的单实例方法,因此@BeforeClass设置也可以是非静态方法,但仍只能运行一次.这是一个设计决定,但是使用TestNG的测试人员必须意识到这一点.

Because of the one-instance-approach of TestNG, the @BeforeClass setup can also be a non-static method, but it is still run only once. It was a design decision, but testers using TestNG must be aware of that.

这篇关于@BeforeClass批注:Junit与TestNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆