Using NUnit to Perform Integration Tests Using ASP.NET WebApi Controllers

I am trying to configure a test using NUnit to run some integration tests on ASP.NET WebApi controllers. I found a couple of articles about hosting with HttpServer, which seems to make things easier without requiring the web server to host everything.

The problem is the only answer I ever get: 404-Not Found.

The controller works when checking manually through a browser or Fiddler. The route definition was copied from the workplace. The api project refers to the test project, and the dll is copied to the same folder as the tests.

Thanks in advance.

Here is the test class

[TestFixture] public class InMemoryTests { private HttpServer Server; private string UrlBase = "http://some.server/"; [TestFixtureSetUp] public void Setup() { var config = new HttpConfiguration(); config.Routes.MapHttpRoute(name: "Default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; Server = new HttpServer(config); } [Test] public void GetOrderStatus() { var client = new HttpClient(Server); var request = createRequest("api/Orders/GetOrderStatus?companyCode=001&orderNumber=1234", "application/json", HttpMethod.Get); using (HttpResponseMessage response = client.SendAsync(request).Result) { Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(response.Content); } } private HttpRequestMessage createRequest(string url, string mthv, HttpMethod method) { var request = new HttpRequestMessage(); request.RequestUri = new Uri(UrlBase + url); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv)); request.Method = method; return request; } private HttpRequestMessage createRequest<T>(string url, string mthv, HttpMethod method, T content, MediaTypeFormatter formatter) where T : class { HttpRequestMessage request = createRequest(url, mthv, method); request.Content = new ObjectContent<T>(content, formatter); return request; } public void Dispose() { if (Server != null) { Server.Dispose(); } } } 
+7
source share
1 answer

I also saw this problem, it seemed to be gone when I moved my test class to the same assembly as my controller; not at all practical for testing, I know.

After a little digging, an error appears that occurs only with its own host, when the calling code does not have the same assembly as the controller, since it failed to load the necessary assemblies.

To confirm that this is your problem / workaround, add this as the first line of your test: -

 Type myType = typeof(myControllerType); 

Additional information: http://forums.asp.net/t/1772734.aspx/1

+8
source

All Articles