Vadim Vadim - 8 days ago 4x
C# Question

How to unit test a method with a `using` statement?

How can I write a unit test for a method that has a using statement?

For example let assume that I have a method


public bool Foo()
using (IMyDisposableClass client = new MyDisposableClass())
return client.SomeOtherMethod();

How can I test something like the code above?

Sometimes I choose not to use
statement and
an object manually. I hope that someone will show me a trick I can use.


If you construct the IMyDisposableClass using a factory (injected into the parent class) rather than using the new keyword, you can mock the IMyDisposable and do a verify on the dispose method call.