Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittesting methods that contain using statements

I am wondering if Unittesting and using statements can really go hand in hand as there is no way to mock the disposable object instantiated in the using statement. How would I be able to effectively unittest a method containing the following using statement?

public void MyMethod()
{
   using(MyDisposableClass disp = new MyDisposableClass())
   {
       ...
   }
}

Are using statements simply forbidden when you are unit-testing?

Any comments appreciated.

like image 885
Fadeproof Avatar asked Dec 11 '08 10:12

Fadeproof


People also ask

Which method is used for unit testing?

Unit Testing Techniques:Black Box Testing - Using which the user interface, input and output are tested. White Box Testing - used to test each one of those functions behaviour is tested. Gray Box Testing - Used to execute tests, risks and assessment methods.

How do you test a statement in C#?

To make the method testable, you'll have to pass an IMyDisposableClass instance into the method or into the class hosting Foo (and make the host class itself implement IDisposable ), so you can use a test double instead of the real thing to verify any interactions with it. Show activity on this post.

What are the three parts of a unit test?

A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior.


1 Answers

No, using statements are certainly not forbidden. But what does MyDisposableClass actually do? It strikes me that this isn't really a matter of the using statement being a problem - it's a matter of the method creating a new object which you want to mock - that's the problem.

Do you genuinely need to mock MyDisposableClass? Can it be passed into MyMethod instead of being created inside it? As ever, the trick is to work out how to hook into the process and inject your own objects when you need to...

like image 71
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet