'Unable to test c# rest controllers via in memory host integration tests
I am new to .net and c# and I am learning how to do integration testing on rest controllers in local. I went through the below link for understanding and created a sample project. https://www.strathweb.com/2012/06/asp-net-web-api-integration-testing-with-in-memory-hosting/
When I start the server and hit controller route it works fine. However, when I run the tests it doesn't work. Looks like http client is thinking there is an actual server which is hosting the service and it throws an error saying unable to connect. But I am trying to do via in memory host server. So this error doesn't make sense to me as there is no server started here. Below is the error:
System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No connection could be made because the target machine actively refused it. [::ffff:127.0.0.1]:80
Below is rest controller code:
namespace restapiproject.Controllers
{
public class TestController : Controller
{
[HttpGet]
public String Get()
{
return "hello controller";
}
}
}
Within Startup.cs the below code is where route mapping is done
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "restapiproject v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}");
});
}
Here is the Integration test code:
[TestClass]
public class IntegrationTestController
{
[TestMethod]
public void TestController()
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(name: "Test", routeTemplate: "Test",
defaults:
new
{
controller = "Test",
action = "get"
});
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
HttpServer _httpServer = new HttpServer(config);
_httpServer.InnerHandler = new HttpClientHandler();
HttpClient client = new HttpClient(_httpServer);
client.BaseAddress = new Uri("http://localhost/");
String url = "http://localhost/test/get";
var request = new HttpRequestMessage
{
RequestUri = new Uri(url),
Method = HttpMethod.Get
};
var response = client.Send(request);
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
}
}
What I think here is when the server is created somehow it is unable to load this controllers within test project. I came across a code snippet where configure the webapi should fix but I am unable to refer this below code as I am getting compilation errors.
WebApiApiConfig.Configure(config); // config of your Web API
Can someone please help me on how do I refer this webapiconfig and also how I make sure to load the controllers in the test project or if this error is something else.
Solution 1:[1]
If you want to run integration tests in process I can recommend the NuGet package Microsoft.AspNetCore.TestHost. It provides an abstraction for networking (no listener on localhost) but you can still test routing, serialization, etc.
[TestClass]
class ControllerTests
{
[TestMethod]
public async Task TestGet()
{
var server = new TestServer(new WebHostBuilder()
.UseWebRoot("...") // configure this if you need static files
.ConfigureAppConfiguration(builder =>
{
// configure this if you need app settings for testing
builder.AddJsonFile("appsettings.json", optional: false);
})
// new .NET 6 minimal syntax doesn't work as easy as this
.UseStartup<Startup>());
HttpClient client = server.CreateClient();
HttpResponseMessage? response = await client.GetAsync("test/get");
response.EnsureSuccessStatusCode();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Danitechnik |
