1

We are creating a web api and I am trying to setup integration testing for the web api, so we don't have to use PostMan to verify if it's working.

When I run the webapi and use PostMan, I am getting the expected result. However, when I try to use in memory hosting and run the webapi for integration testing, it is always returning 404.

Using XUnit - the test class is below.

    public class UnitTest1
{
    private readonly TestServer _server;
    private readonly HttpClient _client;

    public UnitTest1()
    {
        var host = new WebHostBuilder()  
            .UseStartup<Startup>();

        this._server = new TestServer(host);
        this._client = _server.CreateClient();
    }

    [Fact]
    public async void TestMethod1()
    {
        var response = await this._client.GetAsync("api/objects");
        response.EnsureSuccessStatusCode();

        var responseString = await response.Content.ReadAsStringAsync();

        List<obj> result = JsonConvert.DeserializeObject<IEnumerable<obj>>(responseString).ToList();

        Assert.Equal(3, result.Count);
    }
}

The startup class:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

    public void Configure()
    {
        var config = new HttpConfiguration();
        WebApiConfig.Register(config);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }
}

I had to add the configure method in the startup, otherwise test would fail while the class was being initialized.

Neil
  • 629
  • 5
  • 14

1 Answers1

0

You can try something like :

using (HttpConfiguration config = new HttpConfiguration())
{
    config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

    WebApiConfig.Register(config); // If Needed
     FilterConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters); // If Needed

If need more details, you can find here: https://stackoverflow.com/a/49202654/2928038

PKV
  • 773
  • 1
  • 7
  • 17