测试IDisposable和WCF客户端

时间:2010-09-08 21:07:35

标签: c# wcf unit-testing mocking

通常我的客户端代码类似于以下内容:

// SomeOtherServiceClient would be injected in actual code.
ISomeOtherService client = new SomeOtherServiceClient();

...以便我可以模拟测试服务。但现在我有一个WCF服务,其上下文模式设置为PerSession并实现IDisposable

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class SampleService : ISampleService, IDisposable
{
    public void SampleMethod() { ... }
    public void Dispose() { ... }
}

如果我希望将客户端放在using语句中,我还有办法模拟客户端进行测试吗?

// SampleServiceClient would be injected in actual code.
using (var client = new SampleServiceClient())
{
    ...
}

1 个答案:

答案 0 :(得分:1)

如果我理解了这个问题,那就是ISomeOtherService是一个WCF服务合同,即使所有实现的客户端都会实现,也不会实现IDisposable。您可以通过将using语句更改为以下内容来解决此问题:

public void SampleMethod()
{
    //client was injected somehow
    using(this.client as IDisposable)
    {
        ...
    }
}