2016-10-19 4 views
1

저는 Base라는 추상 기본 클래스와 많은 파생 클래스를 가지고 있습니다. D1, D2, D3을 가정 해 봅시다.AutoFixture를 무작위로 여러 TypeRelays 중에서 선택하는 방법은 무엇입니까?

자료 요청이 들어 왔을 때 D1, D2, D3 중 하나를 선택하도록 AutoFixture를 임의로 설정하려면 어떻게해야합니까?

Fixture.Customizations에 각각 D1, D2, D3에 TypeRelay를 추가하면 항상 첫 번째 추가 된 것을 선택하는 것처럼 보입니다.

답변

1

다음 코드를 함께 처리 할 수있었습니다. 어떤 이유로 인해 요청 중 하나가 실패하면, 지정된 기본값으로 폴백되어 실패 증명이되어야합니다. TypeRelay를 정확히 사용하지는 않지만 효과는 본질적으로 동일합니다.

public class RandomCustomization<T> : ICustomization 
{ 
    private readonly Type _defaultType; 
    private readonly Type[] _types; 
    public RandomCustomization(Type defaultType, params Type[] types) 
    { 
     _defaultType = defaultType; 
     _types = types; 
    } 
    public void Customize(IFixture fixture) 
    { 
     fixture.Customize<T>(v => v.FromFactory(new RandomFactory(_defaultType, _types))); 
    } 
} 

public class RandomFactory : ISpecimenBuilder 
{ 
    private readonly Type _defaultType; 
    private readonly Type[] _types; 
    private readonly Random _ran = new Random(); 

    public RandomFactory(Type defaultType, params Type[] types) 
    { 
     _defaultType = defaultType; 
     _types = defaultType.Concat(types).ToArray(); 
    } 
    public object Create(object request, ISpecimenContext context) 
    { 
     var which = _types[_ran.Next() % _types.Length]; 
     var toret = context.Resolve(which); 
     if (toret == null || toret is OmitSpecimen) 
     { 
      toret = context.Resolve(_defaultType); 
     } 
     return toret; 
    } 
}