Reputation: 29
I am working on a .net core web api project and writing some unit tests for my methods. One of my test cases is unable to calculate expected output.
In test project, I have the following code:
_mockBaseDbContext.Setup(c => c.Transactions).Returns(mockTransactions.Object);
var actualResult = await _service.Get(transactionId);
In the web api, I have the corresponding method as follows:
public async Task<TransactionViewModel> Get(Guid id)
{
var transaction = await GetById(id);
var result = _mapper.Map<TransactionViewModel>(transaction);
return result;
}
So, when i run the test case, it finds the transaction
var transaction = await GetById(id); //works fine
but it just can not map the Transaction to TransactionViewModel
_mapper.Map<TransactionViewModel>(transaction); //returns null
I have the mapping profile in startup.cs and it works when I run the web api, I mean I have written an endpoint that takes guid as a parameter and call my meyhod, then it returns the transaction view model without any trouble.
CreateMap<Transaction, TransactionViewModel>()
.ForMember(dest => dest.Client, opt => opt.MapFrom(src => src.Client))
.ForMember(dest => dest.ShopId, opt => opt.MapFrom(src => src.ShopId));
So my question is that is there a way to get the view model that is returned from my Get method? Thanks in advance.
Upvotes: 2
Views: 2659
Reputation: 101
source: https://www.thecodebuzz.com/unit-test-mock-automapper-asp-net-core-imapper/
You can use your profile mapper as follow :
private static IMapper _mapper;
public testContsructor()
{
if (_mapper == null)
{
var mappingConfig = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new UserProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
_mapper = mapper;
}
}
Upvotes: 5