Vadim Vadim - 1 month ago 5
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

Foo
.

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
using
statement and
Dispose()
an object manually. I hope that someone will show me a trick I can use.

Answer

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.

Comments