简体   繁体   English

JUnit 中这两个版本的代码有什么区别?

[英]What is the difference between these two versions of code in JUnit?

What is the difference between the code in Junit: Junit中的代码有什么区别:

class MethodsTest {
    Methods methods = new Methods();
}

and these:还有这些:

class MethodsTest {

    Methods methods;
    @BeforeEach
    void init() {
        methods = new Methods();
    }
}

When to use first code and when to use second code?何时使用第一个代码,何时使用第二个代码?

In the first version, you hope that the particular test runner you're using is creating a new instance of MethodsTest implicitly creating a new instance of Methods when executing a particluar test.在第一个版本中,您希望您使用的特定测试运行器正在创建一个新的MethodsTest实例,在执行特定测试时隐式地创建一个新的Methods实例。 In the second version, you're telling the test runner you're using explicitly to create a new instance of Methods when executing a new test.在第二个版本中,您告诉测试运行器您在执行新测试时显式使用它来创建新的Methods实例。

If there is no inheritance involved, there is no difference.如果不涉及继承,则没有区别。

If you were to extend the MethodsTest class, you could override the init() method, and the overriding method would not necessarily either initialize the field directly, or perhaps indirectly by invoking super.init() ;如果您要扩展MethodsTest类,则可以覆盖init()方法,并且覆盖方法不一定会直接初始化该字段,或者可能通过调用super.init()间接初始化该字段; or it could initialize it differently.或者它可以以不同的方式初始化它。

Personally, I would prefer the first.就我个人而言,我更喜欢第一个。 It's more concise, not overrideable, and its semantics are obvious to anybody familiar with Java, even without JUnit-specific knowledge.它更简洁,不可覆盖,其语义对于熟悉 Java 的任何人来说都是显而易见的,即使没有特定于 JUnit 的知识。

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

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