Home > Net >  How to use AutoMapper in Unit Tests
How to use AutoMapper in Unit Tests

Time:08-01

I can´t use AutoMapper in my Unit Test. It give me this error:

Missing map from Gemvest.Domain.Entities.Note to Gemvest.Application.Notes.Queries.GetById.GetByIdNoteDto. Create using CreateMap<Note, GetByIdNoteDto>.

But I added this in the test setup:

[SetUp]
    public void SetUp(){
        var config = new MapperConfiguration(x => new MapperConfiguration(c =>
        {
            c.CreateMap<Note, GetByIdNoteDto>();
        }));
        _mapper = config.CreateMapper();
    }

Here is the code of unit test:

 public class GetByIdNoteQueryTest
{


    private readonly ApplicationDbContext _context;
    private IMapper _mapper;
    private readonly ICurrentUserService _currentUserService;
    private readonly IDateTime _dateTime;
    public GetByIdNoteQueryTest()
    {


        
        var options = new DbContextOptionsBuilder<ApplicationDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;

        //
        var context = new ApplicationDbContext(options, _currentUserService, _dateTime);
        _context = context;

        _context.Database.EnsureCreated();

    }

    [SetUp]
    public void SetUp(){
        var config = new MapperConfiguration(x => new MapperConfiguration(c =>
        {
            c.CreateMap<Note, GetByIdNoteDto>();
        }));
        _mapper = config.CreateMapper();
    }
    
    [Test]
    public async Task ShouldGetNoteById()
    {
        try{
             //Arrange
        _context.Notes.Add(new Note
        {
            Description = "test"
        });
        _context.SaveChanges();

        var handler = new GetByIdNoteQueryHandler(_context, _mapper);

        var query = new GetByIdNoteQuery()
        {
            Id = 1,
            UserId = 1
        };

        var cltToken = new System.Threading.CancellationToken();

        //Act
        var result = await handler.Handle(query, cltToken);

        //Assert
        Assert.IsNotNull(result);
        Assert.AreEqual("test", result.Description);
        }catch(Exception exc){
            Console.WriteLine(exc);
        }
       

    }

    
}

Here is the code of the service to test:

public class GetByIdNoteQuery : IRequest<GetByIdNoteDto>
{
    public int UserId {get;set;}
    public int Id { get; set; }
}

public class GetByIdNoteQueryHandler : IRequestHandler<GetByIdNoteQuery, GetByIdNoteDto>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;
    public GetByIdNoteQueryHandler(IApplicationDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<GetByIdNoteDto> Handle(GetByIdNoteQuery request, CancellationToken cancellationToken)  
    {
        var noteDB = await _context.Notes.Include(a => a.Proyect).Where(e => e.Id == request.Id).ProjectTo<GetByIdNoteDto>(_mapper.ConfigurationProvider).FirstOrDefaultAsync();
        if (noteDB == null || noteDB.Proyect.UserId != request.UserId)
        {
            throw new NotFoundException($"Event with id {request.Id} not exist)");
        };
        return noteDB;
    }
}

Any idea? Thanks

CodePudding user response:

Your configure action of MapperConfiguration is wrong.

[SetUp]
public void SetUp()
{
    var config = new MapperConfiguration(x =>
    {
        x.CreateMap<Note, GetByIdNoteDto>();
    });
    _mapper = config.CreateMapper();
}
  • Related