Best Practices: Better Way to Test for This?

Hello Community,

I am happy to say that I just wrote my first dotMemory xUnit test. :)  However, I wanted to see if there is an improvement I can make to this test.  I am wanting to test that a certain object does NOT stay in memory.  In order to do that, I have to call another method.  So essentially, this creates two methods: 1 that xUnit/dotMemory calls, and then the "memory" body test.

Here is the example.

I am curious if there is a "better way" of creating this test without creating two methods.  Hope this makes sense.  Please let me know if you have any questions.

Thank you,


Comment actions Permalink
Official comment

Hi Michael,
thanks for the question

As far as I understand, you moved a part of code into separated method in order to references from local variables "first" and "second" will be released before dotMemory.Check call? Are they of type MemoryTestFactory.Result?

Usually, when you test your real code there is no such problem because test calls "production" methods which isolate local variables automatically. But when you just trying dotMemory Unit it can happen that you need to isolate local variables manually. Making a separated method is the best way to do that, you are right. Another way is to set variables to null, but it won't work in debug mode under some versions of .NET. You can read a little bit more about it here.

Comment actions Permalink

Correct Ed!  These references are cached based on the parameter input.  I have gone through a great number of variations of this solution (for reference, it is a PostSharp aspect), but I have finally landed on one that I really like.  So my first test was to ensure that when the factory is no longer referenced, the cached items (in a ConcurrentDictionary) also get cleaned up.

That is a shame about setting variables to null.  That would be perfect!  Perhaps maybe make a way to get dotMemory to always run without this JIT-optimization as a setting?

Comment actions Permalink

FWIW I have created a feature request around this scenario here:

Thank you for any consideration and feedback!


Please sign in to leave a comment.