James McCoy
James McCoy

Reputation: 89

Result from mocking unit test always returns null

I'm currently setting up some unit tests to return ID of the cafes using some mocking, but for some reason the result variable always returns null.

Setup in service class which implements the Get method

public async Task<CafeResponse> Get(int cafeId)
        {
            var cafe= await _cafeRepository.GetByIdAsync(cafeId);

            
            return _mapper.Map<CafeResponse>(cafe);
        }

Unit test setup: Currently the result variable shows null? Not sure if this is due to me setting up the mock incorrectly

        [Fact]
        public async Task Get_ShouldReturnCafeArray_WhenCafesInDatabase()
        {
            //Arrange
            var cafeId = 98;
            var cafeName = "bellas";
            var cafeIdGuid = Guid.NewGuid();
            var cafeDesc = "this is my test";
            var cafeTypeId = 1;


            var cafeDto = new Cafe
            {
                CafeId = cafeId,
                Name = cafeName,
                CafeGuid = cafeIdGuid, 
                Description = cafeDesc,
                CafeTypeId = cafeTypeId,
            
            };

            var expected = new CafeResponse();

            var mockCafe = new Mock<IRepositoryAsync<Cafe>>();
            mockCafe.Setup(x => x.GetByIdAsync(cafeId)).ReturnsAsync(cafeDto);

           
            var mockMapper = new Mock<IMapper>();
            mockMapper.Setup(x => x.Map<Cafe, CafeResponse>(It.IsAny<Cafe>())).Returns(expected);

            //Act
            var cafeService = new CafeService(mockCafe.Object, mockMapper.Object);
            var result = await cafeService.Get(cafeId); //always returns null

           
            //Assert
            mockCafe.Verify(x => x.GetByIdAsync(cafeId), Times.Once);
            Assert.Equal(cafeId, result.CafeId);


        }

Upvotes: 0

Views: 2066

Answers (1)

devNull
devNull

Reputation: 4219

The reason that you're getting a null result with the code that you have is because for IMapper you're mocking:

TDestination Map<TSource, TDestination>(TSource source);

but your actual code is using:

TDestination Map<TDestination>(object source);

So if you just want the test to return your "expected" instance of CafeResponse, then you need to update your Mock<IMapper> setup to be:

mockMapper.Setup(x => x.Map<CafeResponse>(It.IsAny<Cafe>())).Returns(expected);

The more appropriate solution as pointed out in the comments would be to simply create a Mapper instance for your test:

var mapper = new MapperConfiguration(cfg =>
{
    cfg.AddProfile<MyProfile>();
}).CreateMapper();

Otherwise, you're just testing that you're mock is returning what you tell it to and not really verifying any functionality in your code.

Upvotes: 2

Related Questions