In the previous article, we examined an example of writing a unit test. In this article, we want to implement testing for APIs using the xUnit library. For this, we first create an Asp.Net Core Web App project. Then we create a controller called UsersController that displays the information of a user. If the sent ID related to the user is wrong and does not exist in the database, the 404 status code should be returned. For this, we first create the User model:

public class UserModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Then we create a resource to receive user data. In this example, since our goal is API tests, we use a static resource:

public static class UserDataSource
{
    public static List<UserModel> Users
    {
        get
        {
            return new List<UserModel>
            {
                new UserModel
                {
                    Id = 1,
                    Name = "Farhad"
                },
                new UserModel
                {
                    Id  = 2,
                    Name = "Himan"
                },
                new UserModel
                {
                    Id  = 2,
                    Name = "Moji"
                }
            };
        }
    }
}

Then we add a service to receive user information, which includes two methods: GetAll and GetById:

public class UserService : IUserService
{
    public List<UserModel> GetUsers()
    {
        return UserDataSource.Users;
    }
    public UserModel GetById(int id)
    {
        var user = UserDataSource.Users
            .Where(a => a.Id == id)
           .FirstOrDefault();

        return user;
    }
}

Next, we create the controller related to User:

[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
    private readonly IUserService _userService;

    public UsersController(IUserService userService)
    {
        _userService = userService;
    }

    [HttpGet]
    public List<UserModel> Get()
    {
        return _userService.GetUsers();
    }

    [HttpGet("{id:int}")]
    public IActionResult GetById(int id)
    {
        var user = _userService.GetById(id);

        if (user is null)
            return NotFound();

        return Ok(user);
    }
}

In the API for receiving user information using id, if the user information is not found, a response code of 404 should be received. To do this, first create a new xUnit Test Project project. First, you need to add the Asp.Net Core Web App project reference that you created in this project. Then we need an HttpClient to send the request to the Users controller. To test APIs, we need an HttpClient to send requests and also to run the project for which we want to write tests. Microsoft.AspNetCore.Mvc.Testing library gives us these possibilities. The WebApplicationFactory class located in the Microsoft.AspNetCore.Mvc.Testing  library receives a generic type to which we must give the Startup class of the created project to run the project and provide us with the corresponding HttpClient. Next, we need to create a test class named UserControllerTest that receives WebApplicationFactory<Startup> through its constructor and provides us with an HttpClient through the CreateClient method that sends requests to the localhost address that the Asp.Net Core Web App project has implemented:

public class UsersControllerTest : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public UsersControllerTest(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task When_IdIsNotValid_Then_NotFoundStatusCodeShouldBeReturned()
    {
        var httpClient = _factory.CreateClient();

        var userResponse = await httpClient.GetAsync($"/api/users/{-1}");

        userResponse.StatusCode.Should().Be(HttpStatusCode.NotFound);
    }
}

In the following, we have written a test that first creates the HttpClient and then sends a request to the /api/users/-1 address, and since the sent ID is not available in the data source, a response code of 404 should be received. The response check is from the FluentAssertion package. It makes test writing easier. In the same way, we can write tests for all APIs. For example, if the user is not logged in, a 401 response code should be received, or if the user ID is valid, the user's information should be returned in the API.
You can download the source code from Github.

;)

Powered by Froala Editor

Comments