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

2019-02-06 08:17发布

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.

7条回答
家丑人穷心不美
2楼-- · 2019-02-06 08:54

Without a specification for Foo, how can we say how to test it?

  1. Get the specification for Foo.
  2. Write tests to ensure that it meets all specifications and requirements (or a reasonable subset- some functions could require practically infinite amounts of data to test).

I believe you have a second, implicit question in there - which is how to test that use of your MyDisposableClass correctly Disposes of the object when it is freed by exiting an using clause. This is a separate test issue, and shouldn't be combined with the test of Foo, since the specification of Foo shouldn't reference implementation specific details such as the use of your MyDisposabeClass.

I think the other posters have answered this question, so I won't further elaborate.

查看更多
登录 后发表回答