WCF service hosting in unit test

I want to unit test my custom ServiceHostFactory . Unfortunately, I get this InvalidOperationException when calling CreateServiceHost :

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

I can get around this by refactoring my class so that it provides a public method that can be called directly by unit test instead of using its inherited public interface; I don't like changing my interface just for the sake of unit test. I also see another SO answer that recommends spawning a Cassini host, but I would not want to complicate my unit tests this way.

Is there a way around this ServiceHostFactory limitation without resorting to these measures?

+4
source share
2 answers

I understood the question. In my usual ServiceHostFactory I just overrided the protected method CreateServiceHost(Type serviceType, Uri[] baseAddresses) . CreateServiceHost(string constructorString, Uri[] baseAddresses) public CreateServiceHost(string constructorString, Uri[] baseAddresses) method CreateServiceHost(string constructorString, Uri[] baseAddresses) , I was able to create the factory service host without any problems.

Before:

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

After:

 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) { // ... } } 
+5
source

Here is my solution to this problem (I'm not 100% sure if we should do this).

In the unit test device setup, configure the hosting environment (NUnit example):

 [TestFixtureSetUp] public void TestFixtureSetup() { if(!HostingEnvironment.IsHosted) { // The instance constructor hooks up the singleton hosting environment, ewww... new HostingEnvironment(); // Check the hosting environment is fully initialized ServiceHostingEnvironment.EnsureInitialized(); } } 

Then you can freely use your custom ServiceHostFactory from within your unit tests:

 [Test] public void ServiceHostIsCorrect() { // Arrange var serviceType = typeof (string); var factory = new UnityServiceHostFactory(); // Act var serviceHost = factory.CreateServiceHost(serviceType.AssemblyQualifiedName, new Uri[] {}); // Assert Expect(serviceHost, Is.TypeOf<UnityServiceHost>()); var unityServiceHost = (UnityServiceHost)serviceHost; Expect(unityServiceHost.Description.ServiceType, Is.EqualTo(serviceType)); } 
+1
source

All Articles