我怎么能写一个单元测试,以确定是否一个对象被垃圾收集? [英] How can I write a unit test to determine whether an object can be garbage collected?
问题描述
关于<一个href="http://stackoverflow.com/questions/578593/castle-windsor-will-my-transient-component-be-garbage-collected">my previous问题,我需要检查的部件将由温莎城堡被实例化,是否可以被垃圾收集后,我的code。使用它已经完成。我试图从previous问题的答案的建议,但它似乎并没有按预期,至少在我的code。所以我想编写一个单元测试,测试是否特定对象实例可以后我的一些code已经运行垃圾进行回收。
In relation to my previous question, I need to check whether a component that will be instantiated by Castle Windsor, can be garbage collected after my code has finished using it. I have tried the suggestion in the answers from the previous question, but it does not seem to work as expected, at least for my code. So I would like to write a unit test that tests whether a specific object instance can be garbage collected after some of my code has run.
这有可能做一个可靠的方法是什么?
Is that possible to do in a reliable way ?
修改
我现在有一个基于保罗Stovell的回答下面的测试,成功:
I currently have the following test based on Paul Stovell's answer, which succeeds:
[TestMethod]
public void ReleaseTest()
{
WindsorContainer container = new WindsorContainer();
container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();
container.AddComponentWithLifestyle<ReleaseTester>(LifestyleType.Transient);
Assert.AreEqual(0, ReleaseTester.refCount);
var weakRef = new WeakReference(container.Resolve<ReleaseTester>());
Assert.AreEqual(1, ReleaseTester.refCount);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.AreEqual(0, ReleaseTester.refCount, "Component not released");
}
private class ReleaseTester
{
public static int refCount = 0;
public ReleaseTester()
{
refCount++;
}
~ReleaseTester()
{
refCount--;
}
}
我说得对假设的基础上,上面的测试,我可以断定,使用NoTrackingReleasePolicy温莎时,不会造成内存泄露?
Am I right assuming that, based on the test above, I can conclude that Windsor will not leak memory when using the NoTrackingReleasePolicy ?
推荐答案
这就是我通常做的:
[Test]
public void MyTest()
{
WeakReference reference;
new Action(() =>
{
var service = new Service();
// Do things with service that might cause a memory leak...
reference = new WeakReference(service, true);
})();
// Service should have gone out of scope about now,
// so the garbage collector can clean it up
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.IsNull(reference.Target);
}
注:有非常,非常几次,你应该在生产应用程序调用GC.Collect()。但是,测试是否泄漏是地方适当的一个例子。
NB: There are very, very few times where you should call GC.Collect() in a production application. But testing for leaks is one example of where it's appropriate.
这篇关于我怎么能写一个单元测试,以确定是否一个对象被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!