检查内存流量
检查内存流量
当您只需要评估测试中分配的内存量时,可以使用 AssertTraffic 属性。
该属性非常灵活,允许您按对象的类型、接口或命名空间筛选流量数据。
请注意,如果您想通过多个条件筛选内存流量,可以添加任意数量的 AssertTraffic 属性。
[AssertTraffic(AllocatedSizeInBytes = 1000, Types = new[] { typeof(string) })] // starts collecting traffic data automatically
[Test]
public void TestMethod1()
{
... // Some user code
}
通过复杂条件筛选内存流量
在更复杂的场景中(例如需要检查特定时间间隔内的流量时),您应该使用 Traffic 类型。
[DotMemoryUnit(CollectAllocations=true)] // collect traffic data
[Test]
public void TestMethod1()
{
var memoryCheckPoint1 = dotMemory.Check(); // 1
foo.Bar();
var memoryCheckPoint2 = dotMemory.Check(memory =>
{
// 2
Assert.That(memory.GetTrafficFrom(memoryCheckPoint1).Where(obj => obj.Interface.Is<IFoo>()).AllocatedMemory.SizeInBytes,
Is.LessThan(1000));
});
bar.Foo();
dotMemory.Check(memory =>
{
// 3
Assert.That(memory.GetTrafficFrom(memoryCheckPoint2).Where(obj => obj.Type.Is<Bar>()).AllocatedMemory.ObjectsCount,
Is.LessThan(10));
});
}
要标记可以分析内存流量的时间间隔,您应该使用由 dotMemory.Check 创建的检查点(正如您可能猜到的,这个方法只是获取内存快照)。
定义时间间隔起点的检查点会传递给
GetTrafficFrom方法。例如,这行代码断言在
memoryCheckPoint1和memoryCheckPoint2之间的时间间隔内创建的实现IFoo接口的对象总大小小于 1000 字节。您可以使用之前创建的任何检查点作为分析的基础。 因此,这行代码获取当前
dotMemory.Check调用和memoryCheckPoint2之间的流量数据。
dotMemory Unit 还为流量查询提供了替代语法。 您可以使用 ==、 & 和 | 逻辑运算符来组合多个查询。 例如:
Assert.That(memory.GetTrafficFrom(memoryCheckPoint2).Where(obj => obj.Type == typeof(Foo) | obj.Interface == typeof(IEnumerable))
.AllocatedMemory.ObjectsCount, Is.LessThan(10));
最后修改日期: 2025年 9月 28日