Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio: Unit Testing a web project in the same solution

I have a solution with a WebAPI project and a VS Test project.

My tests make calls to the API using RestSharp via a Url rather than instantiating the controller itself and injecting things (context etc).

My question, is there a way to tell the test project to launch the web project via IIS Express when a test run begins? Currently I just run two instances of VS, one with the web projected with debugging started and the other running the test package

like image 798
keithwarren7 Avatar asked Jan 20 '13 00:01

keithwarren7


2 Answers

If you are trying to debug both the test and the service, consider doing this

  1. Launch to debug your Web service in Visual Studio.
  2. Click Debug -> Detach All. IIS Express will keep running.
  3. Set a break point and start Debuging your Unit Test.
  4. (Skip this if you don't need to debug the web service) Click Debug -> Attach to Process. Find iisexpress.exe and attach.

However, you lose Edit and Continue on your web service which was detached.

like image 90
fjch1997 Avatar answered Nov 15 '22 07:11

fjch1997


I wouldn't recommend using the network to unit test Web API. You open yourself up to potential flakiness in the test and you end up testing a whole lot more than the service itself.

But if you really must do so, maybe to test that your client can exchange information with the API, then I'd suggest you look into self-hosting the service:

http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api

Self-hosting lets you start up a server for Web API with just a few lines of code and you could have your tests start up this server in the right places. In most cases, this should behave the same as having your service hosted in IIS Express. But there are some important distinctions. For example, you won't be able to use some System.Web concepts you may be used to (like HttpContext.Current).

Update:

I've written a blog post about testing Web API services that might help - https://docs.microsoft.com/en-us/archive/blogs/youssefm/writing-tests-for-an-asp-net-web-api-service

Hope that helps.

like image 41
Youssef Moussaoui Avatar answered Nov 15 '22 07:11

Youssef Moussaoui