wcf - 在单元测试中托管 WCF 服务

标签 wcf unit-testing

我想对我的自定义 ServiceHostFactory 进行单元测试.不幸的是,我得到了这个 InvalidOperationException调用CreateServiceHost时:

'ServiceHostFactory.CreateServiceHost' cannot be invoked within the current hosting environment. This API requires that the calling application be hosted in IIS or WAS.



我可以通过重构我的类来解决这个问题,以便它公开一个可以由单元测试直接调用的公共(public)方法,而不是使用其继承的公共(public)接口(interface);我讨厌仅仅为了单元测试而改变我的界面。我还看到另一个建议生成 Cassini 主机的 SO 答案,但我不想以这种方式使我的单元测试复杂化。

有没有办法解决这个问题ServiceHostFactory限制而不诉诸这些措施?

最佳答案

我弄清楚了这个问题。在我的自定义 ServiceHostFactory ,我只覆盖了 protected 方法,CreateServiceHost(Type serviceType, Uri[] baseAddresses) .通过覆盖公共(public) CreateServiceHost(string constructorString, Uri[] baseAddresses)方法,我能够毫无问题地构建服务主机工厂。

前:

public class MyServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        // ...
    }
}

后:
public class MyServiceHostFactory : ServiceHostFactory
{
    public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
    {
        return this.CreateServiceHost(typeof(MyService), baseAddresses);
    }

    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        // ...
    }
}

关于wcf - 在单元测试中托管 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11565610/

相关文章:

.net - google mail如何用html5实现新的上传功能?

ios - 如何使用 CocoaPods 分发测试替身?

python 模拟方法返回模拟而不是 return_value?

c# - 单元测试 : Using another method to check the method under test ran correctly

c# - 数据契约(Contract)序列化器可以用于任何第三方网络服务吗

wcf - MsmqIntegrationBinding 是否需要 MsmqMessage

c# - 无法将类型 'ListName[]' 隐式转换为 'System.Collections.Generic.IList<ListName>'

c# - DataContractSerializer 遗漏了一个对象

.net - .NET多线程和单元测试

java - JUnit 会并行运行测试吗?