Eng*_*pan 2 c# unit-testing automapper .net-core asp.net-core
我正在开发一个 .net core Web api 项目,并为我的方法编写一些单元测试。我的测试用例之一无法计算预期输出。
在测试项目中,我有以下代码:
_mockBaseDbContext.Setup(c => c.Transactions).Returns(mockTransactions.Object);
var actualResult = await _service.Get(transactionId);
Run Code Online (Sandbox Code Playgroud)
在web api中,我有相应的方法如下:
public async Task<TransactionViewModel> Get(Guid id)
{
var transaction = await GetById(id);
var result = _mapper.Map<TransactionViewModel>(transaction);
return result;
}
Run Code Online (Sandbox Code Playgroud)
因此,当我运行测试用例时,它找到事务
var transaction = await GetById(id); //works fine
,但它只是无法将事务映射到 TransactionViewModel
_mapper.Map<TransactionViewModel>(transaction); //returns null
Run Code Online (Sandbox Code Playgroud)
我在startup.cs中有映射配置文件,当我运行Web api时它可以工作,我的意思是我已经编写了一个端点,它以guid为参数并调用我的meyhod,然后它毫无问题地返回事务视图模型。
CreateMap<Transaction, TransactionViewModel>()
.ForMember(dest => dest.Client, opt => opt.MapFrom(src => src.Client))
.ForMember(dest => dest.ShopId, opt => opt.MapFrom(src => src.ShopId));
Run Code Online (Sandbox Code Playgroud)
所以我的问题是有没有办法获取从我的 Get 方法返回的视图模型?提前致谢。
来源:https ://www.thecodebuzz.com/unit-test-mock-automapper-asp-net-core-imapper/
您可以按如下方式使用您的个人资料映射器:
private static IMapper _mapper;
public testContsructor()
{
if (_mapper == null)
{
var mappingConfig = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new UserProfile());
});
IMapper mapper = mappingConfig.CreateMapper();
_mapper = mapper;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1577 次 |
| 最近记录: |