处置方法是否应该进行单元测试? [英] Should Dispose methods be unit tested?

查看:58
本文介绍了处置方法是否应该进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#。是否建议对单元测试处理方法?如果是这样,为什么,应该如何测试这些方法?

I am using C#. Is it advised to unit test dispose methods? If so why, and how should one test these methods?

推荐答案

是的,但是可能很难。在 Dispose 实现中通常会发生两件事:

Yes, but it might be hard. There are two things that can generally happen in Dispose implementation:

在这种情况下,很难验证代码是否调用了例如 Marshal.Release 。一种可能的解决方案是注入一个可以进行处理的对象,并在测试过程中向其传递模拟。达到此效果的原因:

In this case it's pretty hard to verify that the code called, for example, Marshal.Release. A possible solution is to inject an object that can do the disposing and pass a mock to it during testing. Something to this effect:

interface ComObjectReleaser {
    public virtual Release (IntPtr obj) {
       Marshal.Release(obj);
    }
}

class ClassWithComObject : IDisposable {

    public ClassWithComObject (ComObjectReleaser releaser) {
       m_releaser = releaser;
    }

    // Create an int object
    ComObjectReleaser m_releaser;
    int obj = 1;
    IntPtr m_pointer = Marshal.GetIUnknownForObject(obj);

    public void Dispose() {
      m_releaser.Release(m_pointer);
    }
}

//Using MOQ - the best mocking framework :)))
class ClassWithComObjectTest {

    public DisposeShouldReleaseComObject() {
       var releaserMock = new Mock<ComObjectReleaser>();
       var target = new ClassWithComObject(releaserMock);
       target.Dispose();
       releaserMock.Verify(r=>r.Dispose());
    }
}



其他类别的处置方法称为



解决方案可能不像上面那么简单。在大多数情况下,Dispose的实现不是虚拟的,因此很难对其进行模拟。

Other classes' Dispose method is called

The solution to this might not be as simple as above. In most cases, implementation of Dispose is not virtual, so mocking it is hard.

一种方法是将其他对象包装在可模拟的包装器中,类似于 System.Web.Abstractions 命名空间用于 HttpContext 类-即定义 HttpContextBase 具有所有虚拟方法的类,这些虚拟方法仅将方法调用委托给实际的 HttpContext 类。

One way is to wrap up those other objects in a mockable wrapper, similar to what System.Web.Abstractions namespace does for HttpContext class - i.e. defines HttpContextBase class with all virtual methods that simply delegates method calls to the real HttpContext class.

有关如何执行类似的操作,请查看 System.IO.Abstractions 项目。

For more ideas on how to do something like that have a look at System.IO.Abstractions project.

这篇关于处置方法是否应该进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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