Search code examples
c#unit-testingidisposablelegacy-code

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.


Solution

  • 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();
        }
    }