如何进行单元测试以`using`声明的方法? [英] How to unit test a method with a `using` statement?

查看:131
本文介绍了如何进行单元测试以`using`声明的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何能写,有一个using语句的方法的单元测试?



例如我们假设我有一个方法

 公共BOOL美孚()
{
使用(IMyDisposableClass客户端=新MyDisposableClass())
{
返回client.SomeOtherMethod();
}
}



如何测试像上面的代码<? / p>

有时候我选择不使用使用语句和的Dispose()对象手动​​。我希望有人会告诉我一招,我可以使用。


解决方案

如果您构建 IMyDisposableClass 使用工厂(注入父类),而不是使用new关键字,你可以嘲笑 IMyDisposable ,做一个验证的Dispose方法调用


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.

解决方案

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.

这篇关于如何进行单元测试以`using`声明的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆