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.
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.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With