JUnit-我应该为在setUp中实例化的tearDown中的资源分配null吗? [英] JUnit - should I assign null to resources in tearDown that were instantiated in setUp?

查看:68
本文介绍了JUnit-我应该为在setUp中实例化的tearDown中的资源分配null吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在阅读一本有关JUnit的书,作者建议使用tearDown方法清空资源.为什么?这不是GC的工作吗?它会严重造成伤害吗?

I am reading one book about JUnit now and writer advises nulling resources in tearDown method. Why? Isn't this GC's job? Can it seriously make any harm?

让我们想到这样的例子:

Lets think of example like this:

public class SomeTest extends TestCase {
  Vector vector;
  List<Object> list;  

  protected void setUp() {
    vector = new Vector();
    list = new ArrayList<Object>();
  }

  // messing with resources
  // adding, deleting, testing whatever

  protected void tearDown() {
    vector = null;
    list = null;
  }
}

您怎么看?是否需要tearDown中的代码?

What do you think? Is that code in tearDown necessary?

推荐答案

是的,确实有必要.

您会看到,JUnit实际上会为每个测试方法创建Test的单独实例,并且Junit3测试运行程序(对于JUnit4而言并非如此)将这些实例保留到整个过程.测试套件已完成.

You see, JUnit will actually create a separate instance of the Test class for each test method, and the Junit3 test runner (not so with JUnit4) will keep these instances around until the entire test suite has finished.

因此,如果您的(JUnit3)测试类具有占用大量内存的字段,那么当您拥有大量测试方法时,很容易耗尽堆空间.当然,如果示例代码中的这些集合仅包含少数短字符串,那就没关系了.

Therefore, if your (JUnit3) test class has fields that take up a lot of memory, you can easily run out of heap space when you have a large number of test methods. Of course, if those collections in your example code only ever contain a handful of short strings, it doesn't matter.

这篇关于JUnit-我应该为在setUp中实例化的tearDown中的资源分配null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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