I wanted to detect whether or not my code generates garbage. So I created the following unit test.
[TestClass]
public class AllocationTest
{
int[] generationCollections = new int[3];
[TestMethod]
public void TestGarbageGeneration()
{
generationCollections[0] = GC.CollectionCount(0);
generationCollections[1] = GC.CollectionCount(1);
generationCollections[2] = GC.CollectionCount(2);
// Test for garbage here
for (int generation = 0; generation < generationCollections.Length; generation++)
{
Assert.AreEqual(GC.CollectionCount(generation), generationCollections[generation]);
}
}
}
I put the code in question where the "Test for garbage here" comment is and the results are unpredictable. My understanding is that this is due to the fact that GC runs on a separate thread and can be triggered by code other than my test at any time.
I tried GC.Collect to forcefully run collections before and after the test code but then realized that that always increment the collection count, so that test always fails.
Is there a meaningful way to test for garbage in a unit test?