Unit Testing Web API using HttpServer or HttpSelfHostServer

Stay Foolish picture Stay Foolish · Feb 5, 2013 · Viewed 6.9k times · Source

I am trying to do some unit testing in for a Web API project. I am going simulate the web API hosting environment. It seems like that I could use In memory host (HttpServer) or self host (HttpSelfHostServer).

Just wondering what are the difference and which technology is good for what and is there any limitation for those options.

Answer

Filip W picture Filip W · Feb 5, 2013

You should use in memory host for end-to-end tests and then test the network connectivity of your environment separately.

For a number of reasons:

  • In memory host, as the name suggests, runs entirely in memory so will be much faster

  • Self host needs to be run with elevated privileges, so your tests will need to be executed within the context of an "admin" identity. This is far from desired. It is especially troublesome if you want to execute tests from i.e. build scripts or from PowerShell, since, as a result, these processes would also have to be started with elevated privileges. Moreover, this will have to happen on any of the servers you test on.

  • In self host you end up testing the given operating system’s networking stack which really is something that shouldn't be tested – since it might differ across different environments (development, staging, QA, production and so on). For example - a given port might not be available. As a result you might get dragged into unnecessary debugging efforts across different machines to even get the tests running.

  • Finally, testing using self-hosting, still doesn't guarantee that the service will run correctly when web-hosted and vice versa - so you might as well just test in memory