2017-10-30 19 views
3

재 시도 메커니즘을 구현해야합니다.FakeItEasy는 다음 호출시 예외 및 반환 값을 위조하도록 구성합니다.

RetryProvider을 테스트하려면 클래스의 가짜가 처음 두 번의 호출에서 예외를 throw하지만 세 번째 호출에서는 유효한 개체를 반환하고 싶습니다. 정상적인 상황

나는 비슷한 원하는 우리가

A.CallTo(() => this.fakeRepo.Get(1)).ReturnsNextFromSequence("a", "b", "c");을 사용할 수 있습니다 (예외를 throw하지 않고) :

  • 퍼스트 콜 :) (새 예외를 던져;
  • 두 번째 호출 : throw new Exception();
  • 세 번째 호출 : return "success";

어떻게하면 위조를 구성 할 수 있습니까? 사전

답변

3
var fakeRepo = A.Fake<IFakeRepo>(); 

A.CallTo(() => fakeRepo.Get(1)) 
    .Throws<NullReferenceException>() 
    .Once() 
    .Then 
    .Throws<NullReferenceException>() 
    .Once() 
    .Then 
    .Returns('a'); 

에서

덕분에 Specifying different behaviors for successive calls에서이에 대한 자세한 내용을 참조하십시오.

3

이 작동합니다 :

public static IThenConfiguration<IReturnValueConfiguration<T>> ReturnsNextLazilyFromSequence<T>(
    this IReturnValueConfiguration<T> configuration, params Func<T>[] valueProducers) 
{ 
    if (configuration == null) throw new ArgumentNullException(nameof(configuration)); 
    if (valueProducers == null) throw new ArgumentNullException(nameof(valueProducers)); 

    var queue = new Queue<Func<T>>(valueProducers); 
    return configuration.ReturnsLazily(x => queue.Dequeue().Invoke()).NumberOfTimes(queue.Count); 
} 

이 같이 호출 :

var funcs = new Queue<Func<string>>(new Func<string>[] 
{ 
    () => throw new Exception(), 
    () => throw new Exception(), 
    () => "a", 
}); 
A.CallTo(() => this.fakeRepo.Get(1)).ReturnsLazily(() => funcs.Dequeue().Invoke()).NumberOfTimes(queue.Count); 

이 확장 방법을 할 수 :

A.CallTo(() => this.fakeRepo.Get(1)) 
    .Throws<Exception>().Twice() 
    .Then 
    .Returns("a"); 

또 다른 방법은 순서처럼 할

A.CallTo(() => this.fakeRepo.Get(1)).ReturnsNextLazilyFromSequence(
    () => throw new Exception(), 
    () => throw new Exception(), 
    () => "a"); 
+1

또는'(). Twice(). Then.Returns ("a")';) –