如何在 AutoMapper 10 中测试自定义 IValueResolver?

问题描述 投票:0回答:1

AutoMapper 10已从ResolutionContext类中删除了公共构造函数(https://docs.automapper.org/en/stable/10.0-Upgrade-Guide.html#the-resolutioncontext-no-longer-has-a-public-构造函数)。我之前一直在创建一个实例来测试自定义值解析器。由于我无法再创建实例,我如何继续测试依赖于解析上下文的值解析器?

c# unit-testing automapper automapper-10
1个回答
0
投票

我在升级 AutoMapper 后遇到了这个问题。之前我们只是将

ResolutionContext
传递到
IValueResolver
Resolve()
方法中进行单元测试:

// Arrange
var resolver = new MyResolver();

var fakeOptions = A.Fake<IMappingOperationOptions>();
var fakeMapper = A.Fake<IRuntimeMapper>();

ResolutionContext resolutionContext = new ResolutionContext(fakeOptions, fakeMapper);

// Act
var resolvedData = resolver.Resolve(Source, Destination, DestinationMember, resolutionContext);

// Assert
// blah blah blah

新的

ResolutionContext
的私有构造函数给工作带来了麻烦,我不想重新设计我们的测试或改变太多,我只是想让它以尽可能少的努力再次工作。前方黑客警报。

现在我只是使用

MapperConfiguration
来构建
Mapper
,并使用反射窃取
Mapper
ResolutionContext
。然后我可以将其传递回我的
Resolve
方法中:

// Arrange
var resolver = new MyResolver();

var configuration = new MapperConfiguration(c => c.AddProfile<MyProfile>());
var mapper = new Mapper(configuration);

// AutoMapper v10 made ResolutionContext protected - use reflection to get the context from the mapper 
ResolutionContext resolutionContext = mapper
    .GetType()
    .GetProperty("DefaultContext", BindingFlags.Instance | BindingFlags.NonPublic)
    .GetValue(mapper) as ResolutionContext;

// Act
var resolvedData = resolver.Resolve(Source, Destination, DestinationMember, resolutionContext);

// Assert
// blah blah blah

希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.