setUp 和 tearDown 的 jUnit 用法

jUnit Usage of setUp and tearDown

作为 jUnit 的新手,我到目前为止所做的是在测试方法本身内设置我的依赖项(即创建对象)。

问题:

  1. Eclipse 会模拟未使用的变量。这是 setUptearDown 的用途吗?

  2. setUp 中创建对象,然后通过 tearDown null 创建对象是一种好习惯吗?

  3. 上述方法还有哪些其他用例?

  4. 使用前套件 setUptearDown 的目的是什么。有人可以举个例子吗?

干杯, 安德鲁

Being new to jUnit what I have done so far is setting up my dependencies (i.e. creating objects) within the test methods itself.

如果它们被正确初始化和清理,那么这种方法没有任何问题。如果不同的测试需要不同的依赖项,你必须这样做。

Eclipse mocks about unused variables, though. Is this what setUp and tearDown are for?

未使用的变量与setUp 和tearDown 方法无关。您应该使用它们或删除它们。

Is it good practice to create objects within setUp

在某些情况下 setUp 方法(或现在的 @Before 注释)是必要的。 通常构造函数和内联初始化也能正常工作。 @Before 注释很有用,如果你在你的测试中有继承或者你想在初始化期间利用 @Rules。

and then null them out via tearDown?

这是个坏主意。 tearDown(或现在的 @After 注释)应用于清理外部资源,如连接和文件,或恢复对应用程序静态状态所做的更改。不需要空字段,因为垃圾收集器无论如何都会回收它们。

What is the purpose of working with pre-Suite setUp and tearDown. Can someone give an example when this comes in handy?

有时您想在测试之间共享一些资源。例如,创建数据库连接的速度很慢。套件方法让您可以为每个套件创建一次它们,而不是为每个测试或每个测试创建一次 class.