HomeController
is private, because you haven't explicitly declared it public. Try making it public:
public class HomeController:ApiController
{
public HttpResponseMessage Get()
{
return this.Request.CreateResponse();
}
}
سؤال
I am working on a set of unit tests, which include testing of HTTP client/server functionality, with a self hosted server. But I can't get even the simplest test to work. HEre is my code
UnitTest1.cs
using System;
using System.Net.Http;
using System.Web.Http.SelfHost;
using NUnit.Framework;
using SomeWebService;
namespace UnitTestProject1
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
var baseAddress = new Uri("http://localhost:9876");
var config = new HttpSelfHostConfiguration(baseAddress);
new Bootstrap().Configure(config);
var server = new HttpSelfHostServer(config);
using (var client = new HttpClient(server))
{
client.BaseAddress = baseAddress;
var response = client.GetAsync("").Result;
Assert.True(response.IsSuccessStatusCode, "Actual status code: " + response.StatusCode);
}
}
}
}
Bootstrap.cs
using System.Web.Http;
namespace SomeWebService
{
public class Bootstrap
{
public void Configure(HttpConfiguration config)
{
config.Routes.MapHttpRoute(name: "API Default", routeTemplate: "{controller}/{id}", defaults: new
{
controller = "Home",
id = RouteParameter.Optional
});
}
}
}
and the HomeController.cs
using System.Net.Http;
using System.Web.Http;
namespace SomeWebService
{
class HomeController:ApiController
{
public HttpResponseMessage Get()
{
return this.Request.CreateResponse();
}
}
}
The test results in:
Actual status code: NotFound
Expected: True
But was: False
What am I doing wrong?
Packages installed
Install-Package Microsoft.Net.Http -version 2.0.20710
Install-Package Microsoft.AspNet.WebApi.SelfHost -version 4.0.20918
Install-Package Microsoft.AspNet.WebApi.Core -version 4.0.20710
المحلول 2
HomeController
is private, because you haven't explicitly declared it public. Try making it public:
public class HomeController:ApiController
{
public HttpResponseMessage Get()
{
return this.Request.CreateResponse();
}
}
نصائح أخرى
If you want your tests to run even faster, you can avoid the whole TCP/IP stack by using a purely in-memory host,
[Test]
public void TestMethod1()
{
var config = new HttpConfiguration();
new Bootstrap().Configure(config);
var server = new HttpServer(config);
using (var client = new HttpClient(server))
{
client.BaseAddress = baseAddress;
var response = client.GetAsync("").Result;
Assert.True(response.IsSuccessStatusCode, "Actual status code: " + response.StatusCode);
}
}