Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does NUnit dispose of objects that implement IDisposable?

Does NUnit dispose of objects that implement IDisposable on cleanup? I realize there are various ways I can get an object disposed of in a method, but, for example, if the method fails prior to the object being disposed - will NUnit take care of it? (For reference, i'm on v2.6+)

The specific reason i'm asking is for a case where an object that implements IDisposable is created, but I am asserting that an exception is thrown upon creation. If the test fails - and the object is created, I do not want to run into memory leak problems.

Example:

//Will the StreamReader instance here be disposed 
//Of if the assertion fails, and the instance is created?
Assert.Throws<Exception>(() => new StreamReader(filename));

I realize that this will work:

Assert.Throws<Exception>(() => 
{
    using (StreamReader sr = new StreamReader(filename)) { }
}

But it just seems like unnecessary code if NUnit will take care of disposing when necessary.

like image 376
user2338408 Avatar asked Apr 26 '16 14:04

user2338408


1 Answers

No, NUnit will not dispose your objects when used that way. NUnit 3.x will dispose test fixtures that are IDisposable, but that is it.

You state that it seems unnecessary to dispose because NUnit can do it for you, but that is incorrect. In the code in your example, it looks to you like you are passing NUnit an IDisposable object, but in fact you are passing a delegate/lambda/code block that happens to contain an IDisposable object.

You will notice that the signature for Assert.Throws is;

public static TActual Throws<TActual>(TestDelegate code) where TActual : Exception

Notice that it takes a TestDelegate, not an object. TestDelegate is just a void delegate,

public delegate void TestDelegate();

You are reading your code as if you are passing in a StreamReader, but you are actually passing in a delegate, or in other words a method that NUnit calls. NUnit doesn't know or care what you do in that method. Like any other method, it is up to you to dispose objects you create.

like image 88
Rob Prouse Avatar answered Sep 28 '22 10:09

Rob Prouse