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

Vadim picture Vadim · Dec 23, 2009 · Viewed 7.8k times · Source

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

mcintyre321 picture mcintyre321 · Dec 23, 2009

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.

public bool Foo()
{
    using (IMyDisposableClass client = _myDisposableClassFactory.Create())
    {
        return client.SomeOtherMethod();
    }
}