我在测试中使用AutoFixture和AutoMoqCustomization。
我有一个服务,它是被测系统的依赖:
ISomeService
{
Task<IEnumerable<int>> Get();
}
我在被测系统中调用它:
var collection = await _someService.Get(); // collection is empty
我不关心集合中的内容,但我需要集合不为空。我是这样做的:
_fixture.Freeze<Mock<ISomeService>>()
.Setup(service => service.Get())
.Returns(Task.FromResult(_fixture.CreateMany<int>()));
看起来应该通过自定义来完成。我创建并注册了一个:
public class TaskCollectionCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customizations.Add(
new FilteringSpecimenBuilder(
new TaskCollectionBuilder(),
new GenericTypeSpecification(typeof(Task<>))));
}
private class TaskCollectionBuilder : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
// never enters here
}
}
}
问题是从未输入过Create方法。任何想法或现成的解决方案?
修改
添加GenericTypeSpecification源
public class GenericTypeSpecification : IRequestSpecification
{
private readonly Type _type;
public GenericTypeSpecification(Type type)
{
_type = type;
}
public bool IsSatisfiedBy(object request)
{
var requestedType = request as Type;
return requestedType != null &&
requestedType.IsGenericType &&
requestedType.GetGenericTypeDefinition() == _type;
}
}
答案 0 :(得分:4)
AutoFixture已经支持开箱即用的任务,正如Characterization Test所示:
[Fact]
public void AutoFixtureAlreadySupportsTasks()
{
var fixture = new Fixture();
var t = fixture.Create<Task<IEnumerable<int>>>();
Assert.NotEmpty(t.Result);
}
因此,您需要配置Test Double服务的所有内容如下:
[Fact]
public void ConfigureMock()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
fixture.Freeze<Mock<ISomeService>>()
.Setup(s => s.Get())
.Returns(fixture.Create<Task<IEnumerable<int>>>());
var svc = fixture.Create<ISomeService>();
Assert.NotEmpty(svc.Get().Result);
}
如果您认为工作太多,您也可以请AutoConfiguredMoqCustomization
代替您这样做:
[Fact]
public void SimplestCustomization()
{
var fixture =
new Fixture().Customize(new AutoConfiguredMoqCustomization());
var svc = fixture.Create<ISomeService>();
Assert.NotEmpty(svc.Get().Result);
}
然而,就个人而言,我不是自动配置的测试双打的忠实粉丝,因为我认为explicit is better than implicit和测试双重配置应该是单元测试的明确部分,因为它描述了Indirect Input用于测试用例。