James McCoy
James McCoy

Reputation: 89

Mocking a service class using unit tests

There is this codebase where we use automapper and have a layer, Cafes. Which has its object for data representation, CafeService.

class CafeService

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

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

How would you go about mocking a mapper in unit tests? Something I haven't done before. This is my unit test so far..

 public async Task Get_ShouldReturnCafeID_WhenCafesInDatabase()
  {

            var cafeDto = new Cafe
            {
                cafeId = 2
            };

           _cafeRepoMock.Setup(x => x.GetByIdAsync(cafeId))
                .ReturnsAsync(cafeDto);

            //Act
            var cafeResponse = await _sut.Get(cafeId);


            ////Assert
            Assert.Equal(cafeId, cafeResponse.cafeId);

}

When I run this test my _mapper currently outputs null assuming that's because I haven't mocked the mapping.

Trying to get my head around how to really test the .Get() which checks if the paramters are passed correctly for the individual dependency calls based on the responses.

Upvotes: 1

Views: 77

Answers (1)

SiarheiK
SiarheiK

Reputation: 837

I believe you have a mapper profile in your code like that:

public class YouMapperProfile: Profile
{
    public YouMapperProfile()
    {
        CreateMap<Cafe, CafeResponse>()
            .ForMember(x => x.Field, o => o.MapFrom(m => m.Field))...;
    }
}

So, you have to create a new Mapper object and provide all mapping profiles there.

var profile = new YouMapperProfile();
var configuration = new MapperConfiguration(cfg => cfg.AddProfile(profile));

If you inject it into constructor manually:

var profile = new YouMapperProfile();
var configuration = new MapperConfiguration(cfg => cfg.AddProfile(profile));
var service = new CafeService(_repoMock.Object, new AutoMapper.Mapper(configuration));

Or if you register dependices with auotfixture:

var fixtureContainer = new Fixture();
fixtureContainer.Customize(new AutoMoqCustomization());
var profile = new YouMapperProfile();
var configuration = new MapperConfiguration(cfg => cfg.AddProfile(profile));
fixtureContainer.Register<IMapper>(() => new AutoMapper.Mapper(configuration));

Upvotes: 1

Related Questions