Skip to main content
 首页 » 编程设计

c#之TaskIEnumerable>> 自定义的 AutoFixture 自动设置返回类型

2024年02月06日13dflying

我在测试中使用 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; 
    } 
} 

请您参考如下方法:

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和 Test Double 配置应该是单元测试的显式部分,因为它描述了 Indirect Input用于测试用例。