c# - 在 using 语句中创建的 Rhino 模拟和对象

标签 c# mocking rhino-mocks using-statement

大多数时候,当我们使用 Rhino 模拟时,它运行良好,但我们在模拟使用 using 语句创建的对象时遇到问题。

我们有一个实现如下的 WCF 代理:

public class MyProxy : System.ServiceModel<IMyProxy>, IMyProxy
{
    public Response DoWork(Request request)
    {
         return base.Channel.DoWork(request);
    }
}

通常在我们的业务层中,我们会有一个属性:

 IProxy MyProxy;

我们可以将其设置为模拟接口(interface)。

但是当我们使用using语句时,我们的业务层是这样的:

using (MyProxy proxy = new MyProxy())
{
}

实例化类的具体实现。

我们如何让业务层使用用 Rhino 模拟创建的模拟?

编辑

事实证明,您不应该对 wcf 代理使用 using 语句 http://msdn.microsoft.com/en-us/library/aa355056.aspx

最佳答案

注入(inject) Func<IProxy>进入你的类(class),并将其存储在一个字段中。

然后你的代码变成了

public class MyClass
{
    private readonly Func<IProxy> createProxy;

    public MyClass(Func<IProxy> createProxy)
    {
        if (createProxy == null)
            throw new ArgumentNullException("createProxy");
        this.createProxy = createProxy;
    }

    public void DoSomething()
    {
        using (IProxy proxy = this.createProxy())
        {
            ...
        }
    }
}

你的单元测试看起来像这样:

[Test]
void MyClass_does_something()
{
    var proxyStub = MockRepository.CreateStub<IProxy>();
    var myClass = new MyClass(delegate { return proxyStub; });

    myClass.DoSomething();

    // make assertions...
}

注意这里有more relationships而不是简单的“A 需要 B”和“A 创造 B”。

我假设 IProxy源自 IDisposable这里。这有点简化:代理实例也可能有容器创建的一次性依赖项。您不能总是假设这些依赖项需要与请求的对象同时处理。这就是为什么最好使用 Owned<T> 的原因。如我在上面链接的博客文章中所示。

关于c# - 在 using 语句中创建的 Rhino 模拟和对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4346679/

相关文章:

c# - 自动发送电子邮件

python - 使用 Flexmock datetime.datetime.now 模拟

perl - 用于 Perl 单元测试的模拟文件系统

.net - 有没有类似 TypeMock 的开源 mocking 框架?

.net - Rhino 模拟错误 : Previous method 'IEnumerator.MoveNext();' requires a return value or an exception to throw

c# - 如何更早发现不良端点?

c# - 使用各种方法将访问者重定向到网站的不同区域?

python - 在 TestCase.setUp() 中模拟

c# - 什么是 Rhino Mocks Repeat?

C# AutoCAD 插件 SQLite - 在极少数情况下找不到错误表