Self-hosted ASP.NET Core 6 Web API sample system test return always 404 Not Found

112 views Asked by At

I have a project in GitHub that name is BSN.IpTables.Api

This project has a simple API as shown here:

[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class HomeController : ControllerBase
{
    public HomeController(ILoggerFactory loggerFactory, IIpTablesSystem ipTables)
    {
        this.logger = loggerFactory.CreateLogger<HomeController>();
        this.ipTables = ipTables;
    }

    [HttpGet]
    [ProducesResponseType(typeof(Response<IpTablesChainSetViewModel>), (int)HttpStatusCode.OK)]
    public IActionResult List()
    {
        return Ok(); // This is just for sample
        return Ok(ipTables.List());
    }

    private readonly ILogger<HomeController> logger;
    private readonly IIpTablesSystem ipTables;
}

I try to write system test for this project in BSN.IpTables.Api.SystemTest

I setup my test project like below

[SetUpFixture]
public class TestSetup
{
    // TODO: Move to BSN.Commons
    public static int GetAvailablePort()
    {
        const ushort MIN_PORT = 3000;
        const ushort MAX_PORT = UInt16.MaxValue - 30;

        IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();

        HashSet<int> usedPorts = Enumerable.Empty<int>()
            .Concat(ipProperties.GetActiveTcpConnections().Select(c => c.LocalEndPoint.Port))
            .Concat(ipProperties.GetActiveTcpListeners().Select(c => c.Port))
            .Concat(ipProperties.GetActiveUdpListeners().Select(c => c.Port))
            .ToHashSet();

        for (int port = MIN_PORT; port <= MAX_PORT; ++port)
        {
            if (!usedPorts.Contains(port)) return port;
        }

        throw new ConfigurationErrorsException("This system does not has any port for using int this application");
    }

    public static RestClient CreateRestClient(string serverAddress)
    {
        RestClient client = new RestClient(serverAddress);
        RestResponse response = client.Execute(request: new RestRequest("api"));
        if (response.ResponseStatus != ResponseStatus.Completed)
        {
            client = new RestClient(TestSetup.ServerUrl);
            if (client.Execute(request: new RestRequest("api")).ResponseStatus != ResponseStatus.Completed)
                throw new ConfigurationErrorsException($"RestClient does not found server in address {TestSetup.ServerUrl}");
        }

        return client;
    }

    public static RestClient CreateDefaultRestClient()
    {
        return new RestClient($"{TestSetup.ServerUrl}");
    }

    [OneTimeSetUp]
    public void Setup()
    {
        var builder = WebApplication.CreateBuilder();

        var startup = new Startup(builder.Configuration);
        startup.ConfigureServices(builder.Services);

        builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
        builder.Host.ConfigureContainer<ContainerBuilder>(startup.ConfigureContainer);
        builder.WebHost.UseUrls(ServerUrl);

        app = builder.Build();

        startup.Configure(app, app.Environment);

        app.StartAsync().Wait();
    }

    [OneTimeTearDown]
    public void TearDown()
    {
        app.StopAsync().Wait();
    }

    public static string ServerUrl
    {
        get;
    } = Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? $"{DEFAULT_SERVERL_URL}:{GetAvailablePort()}";

    public const string DEFAULT_PREFIX_URL = "api/v1";
    private WebApplication app;
    private const string DEFAULT_SERVERL_URL = "http://localhost";
}

After that I write simple test like below in HomeControllerTest

[TestFixture]
public class HomeControllerTest 
{
    [SetUp]
    public void Initialize()
    {
        client = TestSetup.CreateDefaultRestClient();
    }

    [Test]
    public void List_ShouldBeOk()
    {
        RestRequest request = new RestRequest($"{TestSetup.DEFAULT_PREFIX_URL}/{HOME_CONTROLLER_ROUTE_PREFIX}");
        RestResponse response = client.Get(request);
        response.StatusCode.Should().Be(HttpStatusCode.OK);
    }

    private RestClient client;
    private const string HOME_CONTROLLER_ROUTE_PREFIX = "Home";
}

My problem is when run this test, I got exception, because I got an Http 404 Not Found error, instead of 200 OK.

Am I correctly setup ASP.NET Core 6 Web API in the system test?

0

There are 0 answers