单元测试内存泄漏 [英] Unit testing memory leaks

查看:132
本文介绍了单元测试内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存在大量内存泄漏的应用程序.例如,如果打开一个视图并将其关闭10倍,则由于未完全清除视图,因此我的内存消耗增加了.这些是我的内存泄漏.从测试驱动的角度来看,我想编写一个测试来证明我的泄漏,并(在修复泄漏之后)断言我已修复它.这样,以后我的代码就不会被破坏.简而言之:

I have an application in which a lot of memory leaks are present. For example if a open a view and close it 10 times my memory consumption rises becauses the views are not completely cleaned up. These are my memory leaks. From a testdriven perspective i would like to write a test proving my leaks and (after I fixed the leak) asserting I fixed it. That way my code won't be broken later on. So in short:

有没有办法断言我的代码没有从单元测试中泄漏内存?

Is there a way to assert that my code is not leaking memory from a unit test?

例如我可以做这样的事情吗?

e.g. Can i do something like this:

objectsThatShouldNotBeThereCount = MemAssertion.GetObjects<MyView>().Count;
Assert.AreEqual(0, objectsThatShouldNotBeThereCount);

我对配置文件不感兴趣.我使用了Ants profiler(我非常喜欢),但也想编写测试以确保泄漏"不会再次出现

I am not interested in profiling. I use Ants profiler (which I like a lot) but would also like to write tests to make sure the 'leaks' don't come back

我正在使用C#/Nunit,但是对任何对此有哲学认识的人都感兴趣.

I am using C# / Nunit but am interesed in anyone having a philosophy on this...

推荐答案

当托管类型使用非托管资源时,经常会引起内存泄漏.

Often memory leaks are introduced when managed types use unmanaged resources without due care.

一个典型的例子是System.Threading.Timer,它使用回调方法作为参数.由于计时器最终使用了非托管资源,因此引入了新的GC根目录,该根目录只能通过调用计时器的Dispose方法来释放.在这种情况下,您的类型还应该实现IDisposable,否则该对象将永远无法被垃圾回收(泄漏).

A classic example of this is the System.Threading.Timer which takes a callback method as a parameter. Because the timer ultimately uses an unmanaged resource a new GC root is introduced which can only be released by calling the timer's Dispose method. In this case your type should also implement IDisposable otherwise this object can never be garbage collected (a leak).

您可以通过执行以下操作来为此情况编写单元测试:

You can write a unit test for this scenario by doing something similar to this:

var instance = new MyType();

// ...
// Use your instance in all the ways that
// may trigger creation of new GC roots
// ...

var weakRef = new WeakReference(instance);

instance.Dispose();
instance = null;

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.IsFalse(weakRef.IsAlive);

这篇关于单元测试内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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