Search code examples
c#xunit

xUnit GET results returning null


I'm new to unit testing and have been working on some simple tests but, am having issues trying to use count() to check the returned data.

Here is my test

        [Fact]
        public async void Should_Call_Controller_Get_Return_200()
        {
            // Arrange
            var context = new HotelListingDbContext(dbContextOptions);
            var countriesService = new CountriesRepository(context, _mapper);
            var controller = new CountriesController(_mapper, countriesService);

            // Act
            var data = await controller.GetCountries();

            // Assert
            Assert.IsType<OkObjectResult>(data.Result);  
            data.Result.Should().NotBeNull();
            data.Value.Count.Should().Be(3);  // <<< Object reference not set to an instance of an object.
        }

When I debug, data contains 3 items as per below:

results of getCountries()

Could someone please explain what I should do? I can see that Value is null.

I have tried data.Result.Value.Count but the error states: "ActionResult does not contain a definition for Value" which is confusing me. I have also looked at using Assert.Collection but not sure this is relevant.

I have been looking at the MS docs for unit testing trying to apply it to my project, but am stuck here. I guess it's something to do with the ActionResult and a step I am missing.


Solution

  • In order to access the derived type properties with a specific type you should first cast the result to that specific type.

    Considering the fact that you are using fluent assertions you can use something similar to:

    data.Result.Should().BeOfType<OkObjectResult>()
        .Which.Value.Should().BeOfType<List<GetCountryDTO>>()
        .Which.Should().HaveCount(3);
    

    Hope it helps,