gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:46:06 24 4
gpt4 key购买 nike

大多数时候,当我们使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com