Home > Mobile >  Mapping always returning null
Mapping always returning null

Time:08-10

Line var job = _mapper.Map<DataAccess.Domain.Lab.Job>(jobViewModel); gives error job variable is always returning null while running the unit test i have added the mapping for Jobs Profile `

Below is the code:

JobTest.cs class

public class JobTests
    {
        private static Mock<IMapper> _mapper;
     
     
        public JobTests()
        {
            if (_mapper == null)
            {
                _mapper = new Mock<IMapper>();
                _mapper.Setup(x => x.ConfigurationProvider.AssertConfigurationIsValid());
                _mapper.Setup(x => x.ConfigurationProvider)
                    .Returns(
                        () => new MapperConfiguration(
                            cfg =>
                            {
                                cfg.AddProfile<JobsProfile>();
                               
                                //cfg.CreateMap<AddJobCommand,JobsProfile > ();
                                //cfg.CreateMap<JobViewModel, AddJobCommand>();
                                //cfg.CreateMap<AddJobCommand,JobViewModel>();

                            }));
                
            }
        }

        [Fact]
        public async Task AddJob_AddSingleEntry()
        {

            var mapperMock = new Mock<IMapper>();
            
            var data = JobData.AddFakeJobList();           
            var mockSet = FakeDbSetup.GetMockDbSet<DataAccess.Domain.Lab.Job>(data);           
           
            var mockContext = FakeDbSetup.GetMockDbContext();            
            mockSet.Setup(x => x.AsNoTracking()).Returns(mockSet.Object);
            mockContext.Setup(c => c.Jobs).Returns(mockSet.Object);

         

            AddJobCommandHandler handler = new AddJobCommandHandler(mockContext.Object, _mapper.Object);
            JobViewModel vm= JobData.AddFakeJobList2();
            AddJobCommand command = new AddJobCommand(vm);
            //var stubScheduleCommand = new Mock<AddJobCommand>(mockContext.Object);           
            
            var job = await handler.Handle(command, new System.Threading.CancellationToken());
            Assert.NotNull(job);
            }
        

    }

AddJobCommand.cs

public class AddJobCommandHandler : IRequestHandler<AddJobCommand, JobViewModel>
    {
        private readonly IDrillingFluidsContext _context;
        private readonly IMapper _mapper;

        public AddJobCommandHandler(IDrillingFluidsContext context, IMapper mapper)
        {
            (_context, _mapper) = (context, mapper);
        }

        public async Task<JobViewModel> Handle(AddJobCommand command, CancellationToken cancellationToken)
        {
            if (command.JobViewModel == null) throw new InvalidOperationException("Empty request.");
            var jobViewModel = command.JobViewModel;
          
            try
            {
                var job = _mapper.Map<DataAccess.Domain.Lab.Job>(jobViewModel);
                
                _context.Set<DataAccess.Domain.Lab.Job>().Add(job);
                if (job.Notes!= null)
                { 
                    var newNote = job.Notes.FirstOrDefault(n => n.IsNew);
                    if (newNote != null)
                    {
                        newNote.JobId = job.Id;
                        _context.Set<DataAccess.Domain.Lab.JobNote>().Attach(newNote);
                        _context.Entry(newNote).State = EntityState.Added;
                    }
                }
                if (string.IsNullOrWhiteSpace(job.Name))
                {
                    job.Name = await GenerateJobName(job);                   
                }
                await _context.SaveChangesAsync();
                jobViewModel.Id = job.Id;
                return jobViewModel;
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                        eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                            ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
            catch (DbUpdateException e)
            {
                throw;
            }
            catch (Exception e)
            {
                throw;
            }
        }   

I want the JobViewModel data to be added to the the variable jobs.But it always returns null.This works fine when i am trying to call this method via PostMan.

CodePudding user response:

The problem is that the code uses a mocked mapper that has no setup for the Map method. If there is no setup, the method will return null (for MockBehavior.Loose`).

If you want the Map method to return a value, you need add a setup, e.g.:

[Fact]
public async Task AddJob_AddSingleEntry()
{        
    var data = JobData.AddFakeJobList();           
    var mockSet = FakeDbSetup.GetMockDbSet<DataAccess.Domain.Lab.Job>(data);           
    var mockContext = FakeDbSetup.GetMockDbContext();            
    mockSet.Setup(x => x.AsNoTracking()).Returns(mockSet.Object);
    mockContext.Setup(c => c.Jobs).Returns(mockSet.Object);

    AddJobCommandHandler handler = new AddJobCommandHandler(mockContext.Object, _mapper.Object);
    JobViewModel vm= JobData.AddFakeJobList2();
    AddJobCommand command = new AddJobCommand(vm);
    //var stubScheduleCommand = new Mock<AddJobCommand>(mockContext.Object);
    var job = new DataAccess.Domain.Lab.Job() 
    {
      // Initialize job as needed
    };           

    _mapper.Setup(x => x.Map<DataAccess.Domain.Lab.Job>(vm))
      .Returns(job);
    
    var job = await handler.Handle(command, new System.Threading.CancellationToken());
    Assert.NotNull(job);
}

In the constructor it is not necessary to add setups for the configuration provider if you are using a mocked mapper. So you can setup the _mapper simply like this:

public JobTests()
{
    _mapper = new Mock<IMapper>();
}
  • Related