Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hosting WCF service in Unit Test using ServiceHost

I am trying to write some unit tests that test the endpoints for my WCF service and to do this I want to host the service within the unit tests itself rather than in IIS. I have found this article that I have read through and made the changes so I am hosting it using ServiceHost and I can see that the unit tests are trying to run it but I seem to be hitting a bit of a problem.

When I run the tests, I get the following error at the point of opening the service:

This service requires ASP.NET compatibility and must be hosted in IIS. Either host the service in IIS with ASP.NET compatibility turned on in web.config or set the AspNetCompatibilityRequirementsAttribute.AspNetCompatibilityRequirementsMode property to a value other than Required.

This is being caused by the following attribute setting on my services class:

[AspNetCompatibilityRequirements( RequirementsMode = AspNetCompatibilityRequirementsMode.Required )]

I have then tried to add the following into my app.config but it doesn't seem to make any difference:

<system.serviceModel>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>

Any ideas how I can get past this issue?

like image 926
Richard Hooper Avatar asked Apr 26 '11 11:04

Richard Hooper


1 Answers

As stated by the error message, the ASP.NET compatibility mode requires the WCF service to be hosted in an ASP.NET web server.

If you wish to run some integration tests against your WCF service on your local machine you can always host the service in the Visual Studio Development Server (a.k.a. Cassini). I highly recommend you to take a look at CassiniDev, an open source library that allows to run a lightweight ASP.NET web server in process, which is especially useful for unit testing scenarios.

Here's an example of how you would use CassiniDev in a unit test using MSTest:

[TestClass]
public class MyServiceTest
{
    private CassiniDevServer host;

    [TestInitialize]
    public void SetUp()
    {
        var host = new CassiniDevServer();
        host.StartServer(@"RelativePathToServiceProjectDir", 8080, "/", "localhost");
    }

    [TestCleanup]
    public void TearDown()
    {
       host.StopServer();
    }
}

Related resources:

  • CassiniDev Documentation
  • Using CassiniDev with unit testing frameworks and continuous integration
like image 98
Enrico Campidoglio Avatar answered Oct 22 '22 11:10

Enrico Campidoglio