为了确保我的 AutoMapper 映射不会爆炸,我有一个类似于以下内容的测试类:
public class MapperTests
{
private readonly IMapper _mapper; // from AutoMapper
private readonly IFixture _fixture;
public MapperTests()
{
_mapper = SetUpAutoMapper();
_fixture = new Fixture();
}
[Theory]
[InlineData(typeof(Foo), typeof(Bar))]
[InlineData(typeof(Boo), typeof(Far))]
// etc ...
public void CanMapTypes(Type inputType, Type outputType)
{
var input = _fixture.Create(inputType);
// throws exceptions if something's broken:
_mapper.Map(input, outputType)
}
}
我刚刚发现_fixture.Create(inputType)
实际上并没有创建该类型的实例(例如,第一个测试中的Foo
),而是System.Type
的实例。 当然,这使我的测试毫无用处。
我查看了可用的方法(仅浏览 IntelliSense),但找不到似乎符合我期望的方法。 有没有办法在这里做我想做的事; 基本上创建一个在运行时提供的类型的实例?
好像知道怎么回事了😄
如果您尝试AutoFixture v4 ,您会发现此代码无法编译。 原因是我们将混淆的Create()
方法重载提取到一个单独的包中,因此只有知道自己在做什么的用户才能使用它们。
```c#
_fixture.Create(inputType);
It might look that you are making a request of `typeof(Foo)` here, however in reality you are passing this argument as a `seed` and the actual request type is `typeof(Type)`. To fix the issue please tune a bit your code:
```c#
public class Foo
{
}
[Theory]
[InlineData(typeof(Foo))]
public void TestTypeRequest(Type requestType)
{
var fixture = new Fixture();
var result = fixture.Create(requestType, new SpecimenContext(fixture));
Assert.IsAssignableFrom<Foo>(result);
}
API 可能不简洁,但是您的场景并不常见,所以应该没问题。
让我知道这是否有帮助😉
谢谢!
通过阅读通用fixture.Create<T>()
对象的源代码,找出它最终结束的位置,我还发现这是有效的:
var input = new SpecimenContext(_fixture).Resolve(sourceType);
我想它们或多或少是等价的 :) 非常感谢!
@tlycken确实,两个片段都做同样的事情,而您的选择看起来好多了:)如果需要,将来会使用它:脸红:
最有用的评论
谢谢!
通过阅读通用
fixture.Create<T>()
对象的源代码,找出它最终结束的位置,我还发现这是有效的:我想它们或多或少是等价的 :) 非常感谢!