我希望有人能帮助我。当前,我们正在将AutoMapper从v6升级到v9-我们将升级到v10,但是无法创建新的ResolutionContext
会影响我们的单元测试。也就是说,使用v9进行单元测试AutoMapper转换器时,我们仍然遇到以下问题...
ConverterClass:
public class FooBarConverter :
ITypeConverter<FooSourceObject,BarDestinationObject>
{
/// <inheritdoc/>
public virtual BarDestinationObjectConvert(FooSourceObjectsource,BarDestinationObjectdestination,ResolutionContext context)
{
EnsureArg.IsnotNull(source,nameof(source));
switch (source.Type)
{
case SomeType.None:
return context.Mapper.Map<NoneBarDestinationObject>(source);
case SomeType.FixedAmount:
return context.Mapper.Map<FixedBarDestinationObject>(source);
case SomeType.Percentage:
return context.Mapper.Map<PercentageBarDestinationObject>(source);
default:
throw new ArgumentOutOfRangeException(nameof(source));
}
}
在AutoMapper 6中,我们进行了以下单元测试(使用Xunit):
public class FooBarConverterTests
{
private readonly FooBarConverter target;
private readonly Mock<IRuntimeMapper> mockMapper;
private readonly ResolutionContext resolutionContext;
public FooBarConverterTests()
{
this.mockMapper = new Mock<IRuntimeMapper>();
this.resolutionContext = new ResolutionContext(null,this.mockMapper.Object);
this.target = new FooBarConverter();
}
[Fact]
public void FixedAmountFooModel_ConvertsTo_FixedBarDomainmodel()
{
// Arrange
var input = new Foo
{
Type = SomeType.FixedAmount
};
var expected = new Domainmodels.FixedBarDestinationObject();
this.mockMapper.Setup(x => x.Map<FixedBarDestinationObject>(It.IsAny<FooSourceObjectsource>()))
.Returns(expected);
// act
var actual = this.target.Convert(input,It.IsAny<BarDestinationObjectdestination>(),this.resolutionContext);
// Assert
actual.ShouldSatisfyAllConditions(
() => actual.ShouldNotBeNull(),() => actual.ShouldBeAssignableTo<Domainmodels.FixedBarDestinationObject>());
this.mockMapper.Verify(x => x.Map<Domainmodels.FixedBarDestinationObject>(input));
}
}
从本质上讲,这可以正常工作,但是由于升级到v9,映射设置在通过解析上下文时会丢失。意味着对Mapper.Map<FixedBarDestinationObject>()
的最终调用始终返回null
。
我了解到ResolutionContext
可能有所更改,但是我不了解如何解决此问题并确保将模拟映射传递到基础转换器。
感谢您的帮助或建议。