java - Junit实例创建分别通过方法或类

标签 java junit nunit

最近,我正在阅读《Growing Object-Oriented Software, Guided by Tests》一书,我对他们所说的 Junit 行为的描述感到困惑。

如果我理解作者所说的,Junit 会在每个测试方法中创建一个测试类的新实例,以确保它们彼此隔离。

To run a test, JUnit creates a new instance of the test class and calls the relevant test method. Creating a new test object each time ensures that the tests are isolated from each other, because the test object’s fields are replaced before each test. This means that a test is free to change the contents of any of the test object fields.

然后他们说在 NUnit (.Net) 中是不同的,因为它为所有测试方法重用相同的测试对象,因此您需要使用 SetupsTearDowns.

NUnit Behaves Differently from JUnit Those working in .Net should note that NUnit reuses the same instance of the test object for all the test methods, so any values that might change must either be reset in [Setup] and [TearDown] methods (if they’re fields) or made local to the test method.

我认为 JUnit 的行为就像它们描述的 NUnit 行为一样,因此您的类实例可以在同一个类中重用,并且您可以使用 Setups 和 TearDown 来重置它们。

因此,JUnit 的行为方式是,它在每个方法中实例化测试类,否则实例化一次测试类。

也许我不明白作者的意思。它们的意思是什么?

最佳答案

JUnit 为每个测试实例化测试类(也称为用 @Test 注释的方法)。

设置和拆卸方法只是为了帮助您编写清晰且易于阅读的测试 - 通过提取测试环境的常见设置、先决条件和验证,这样就不会弄乱测试本身。

  1. 环境设置是静态的,并且可以在类中的所有测试中共享 - 可以只创建一次 - @BeforeClass@AfterClass 注解(注意方法必须是静态的)

  2. 环境设置特定于每个测试,不能在类中的所有测试之间共享 - @Before@After 注释

关于java - Junit实例创建分别通过方法或类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44954444/

相关文章:

Java Spring 远程处理选项

java - 返回今天前N天的测试方法

java - 如何使用@IfProfileValue 来测试配置文件是否处于 Activity 状态?

f# - 如何让 NUnit 运行未由模块导出的 F# 测试

asp.net-mvc - 寻找对呈现局部 View 的 Controller 扩展进行单元测试的方向

nunit - Unity Nunit 和 Rhino 模拟

Java 和 Windows?

Java - 将字符串映射到带有枚举的接口(interface)的实现?

java - Substance UI 和自定义 JComponent 的 TitledBorder 问题

java - Junit @Rule 和 Maven Checkstyle 插件