检查对象
检查特定类型的对象
检查特定类型的对象是发现代码中内存泄漏的主要方法。
[Test]
public void TestMethod1()
{
var foo = new Foo();
foo.Bar();
// 1
dotMemory.Check(memory => //2
Assert.That(memory.GetObjects(where => where.Type.Is<Goo>()).ObjectsCount, Is.EqualTo(0))); // 3
GC.KeepAlive(foo); // prevent objects from GC if this is implied by test logic
}
一个 lambda 被传递给静态 dotMemory 类型的
Check方法。 此方法的作用是获取托管堆的转储。 仅当您使用 在 dotMemory Unit 下运行测试 运行测试时,才会调用此方法。传递给 lambda 的 Memory 类型的
memory对象包含当前执行点的所有内存数据。GetObjects 方法返回一组与另一个 lambda 中传递的条件匹配的对象。 例如,这行代码的作用是通过仅保留
Goo类型的对象来切片内存。 NUnit 的Assert表达式断言应该有 0 个Foo类型的对象。
根据多个条件选择对象
要通过多个条件切片数据,您可以构建 GetObjects 调用的链。 ObjectSet 类型有两个可以在测试断言中使用的属性: ObjectsCount 和 SizeInBytes。
Assert.That(memory.GetObjects(where => where.Type.Is<Foo>())
.GetObjects(where => where.Generation.Is(Generation.LOH).ObjectsCount, Is.EqualTo(0));
dotMemory Unit 还提供了对象集查询的替代语法。 您可以使用 ==、 & 和 | 逻辑运算符来组合多个查询。 例如:
Assert.That(memory.GetObjects(where => where.Type == typeof(Foo) & where.Generation == Generation.LOH)
.ObjectsCount, Is.EqualTo(0));
请注意,开放泛型类型和接口也受支持。 例如:
public interface IGenericInterface<T1, T2> { }
...
dotMemory.Check(memory =>
Assert.That(memory.GetObjects(where =>
where.Interface.Is(typeof(IGenericInterface<,>)).ObjectsCount, Is.EqualTo(0)));
最后修改日期: 2025年 9月 28日