问题
I'm trying to setup a test using NUnit to perform some integration testing of ASP.NET WebApi controllers. I've found a couple articles discussing In-Memory hosting using HttpServer that appears to simplify things by not needing a web server hosting everything.
- ASP.NET Web API: in-memory hosting
- ASP.NET Web API integration testing with in-memory hosting
The problem is the only response I ever get is 404-Not Found.
The controller are working when manually tested via a browser or Fiddler. The route definition was copied from the working site. The api project is referenced by the test project and the dll is getting copied to the same folder as the tests.
Thanks in advance.
Here's 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();
}
}
}
回答1:
I was seeing this problem also, seemed to go away when I moved my test class into the same assembly as my controller; generally not practical for testing I know.
After a bit of digging it appears there's a bug that only occurs with self host when the calling code doesn't share the same assembly as the controller as it hasn't managed to load the required assemblies.
To confirm this is your problem / temporarily workaround add this as the first line of your test: -
Type myType = typeof(myControllerType);
More info at : http://forums.asp.net/t/1772734.aspx/1
来源:https://stackoverflow.com/questions/11676828/using-nunit-to-perform-integration-tests-with-asp-net-webapi-controllers