Search code examples
c#unit-testingasp.net-coremoqxunit

Unit Testing API Call


I am using .NET Core with xUnit/Moq to create unit tests. I would like to create a unit test for the following API call:

[HttpGet("{zip}")]
public IActionResult Get(int zip)
{
    //debugging here shows the repository has the object
    //but the result is always null
    Location result = repository[zip];
    if(result == null)
    {
        return NotFound();
    }
    else
    {
        return Ok(result);
    }
}

The unit test I have (that's failing) is:

[Fact]
public void Api_Returns_Json_Object()
{
    //Arrange
    Mock<IRepository> mockRepo = new Mock<IRepository>();
    mockRepo.Setup(m => m.Locations).Returns(new Location[]
    {
        new Location
        {
            zip = 88012,
            type = "STANDARD",
            state = "NM"
        }
    });

    //Arrange
    ApiController controller = new ApiController(mockRepo.Object);

    // Act
    var response = controller.Get(88012);

    // Assert
    Assert.True(response.Equals(HttpStatusCode.OK));
}

When I debug, the repository shows the correct Location object, but the result is always null, returning a NotFound() status code.

If I test the response with PostMan it works correctly.

Here are the relevant IRepository members:

IEnumerable<Location> Locations { get; }
Location this[int zip] { get; }

Solution

  • Based on what is accessed within the method under test, the wrong member was set up when arranging the test

    [Fact]
    public void Api_Returns_Json_Object() {
        //Arrange
        int zip = 88012;
        var location = new Location
        {
            zip = zip,
            type = "STANDARD",
            state = "NM"
        };
    
        Mock<IRepository> mockRepo = new Mock<IRepository>();
        mockRepo.Setup(m => m[zip]).Returns(location);
        var controller = new ApiController(mockRepo.Object);
    
        // Act
        var response = controller.Get(zip);
        var okResult = response as OkObjectResult;
    
        // Assert
        Assert.NotNull(okResult);
        Assert.Equal(location, okResult.Value);
    }