수색…


암시 적으로 호출 순서 유효성 검사

테스트 할 메소드가 한 호출의 정보를 사용하여 후속 호출을 전달하는 경우 예상되는 순서대로 메소드를 호출하는 데 사용할 수있는 한 가지 방법은 이러한 데이터 흐름을 반영하도록 기대치를 설정하는 것입니다.

주어진 테스트 방법 :

public void MethodToTest()
{
    var str = _utility.GetInitialValue();

    str = _utility.PrefixString(str);
    str = _utility.ReverseString(str);

    _target.DoStuff(str);
}

PrefixStringReverseString 을 통해 GetInitialValue 데이터를 DoStuff 에 전달하여 정보가 검증되는 기대치를 설정할 수 있습니다. 임의의 메소드가 부적절하게 호출되면, 최종 데이터가 잘못되어 테스트가 실패합니다.

// Create mocks
var utilityMock = new Mock<IUtility>();
var targetMock = new Mock<ITarget>();

// Setup expectations, note that the returns value from one call matches the expected
// parameter for the next call in the sequence of calls we're interested in.
utilityMock.Setup(x => x.GetInitialValue()).Returns("string");
utilityMock.Setup(x => x.PrefixString("string")).Returns("Prefix:string");
utilityMock.Setup(x => x.ReverseString("Prefix:string")).Returns("gnirts:xiferP");

string expectedFinalInput = "gnirts:xiferP";

// Invoke the method to test
var sut = new SystemUnderTest(utilityMock.Object, targetMock.Object);
sut.MethodToTest();

// Validate that the final call was passed the expected value.
targetMock.Verify(x => x.DoStuff(expectedFinalInput));

콜백을 사용하여 호출 순서 확인

Strict Mocks를 사용하고 싶지 않거나 사용하지 않으려는 경우 MockSequence 를 사용하여 호출 순서의 유효성을 검사 할 수 없습니다. 다른 방법은 콜백을 사용하여 예상 된 순서대로 Setup 기대치가 호출되는지 확인하는 것입니다. 주어진 다음의 테스트 방법 :

public void MethodToTest()
{
    _utility.Operation1("1111");
    _utility.Operation3("3333");
    _utility.Operation2("2222");
}

다음과 같이 테스트 할 수 있습니다.

// Create the mock (doesn't have to be in strict mode)
var utilityMock = new Mock<IUtility>();

// Create a variable to track the current call number
int callOrder = 1;

// Setup each call in the sequence to be tested.  Note that the callback validates that
// that callOrder has the expected value, then increments it in preparation for the next
// call.
utilityMock.Setup(x => x.Operation1(It.IsAny<string>()))
           .Callback(() => Assert.AreEqual(1, callOrder++, "Method called out of order") );
utilityMock.Setup(x => x.Operation2(It.IsAny<string>()))
           .Callback(() => Assert.AreEqual(2, callOrder++, "Method called out of order") );
utilityMock.Setup(x => x.Operation3(It.IsAny<string>()))
           .Callback(() => Assert.AreEqual(3, callOrder++, "Method called out of order") );


// Invoke the method to be tested
var sut = new SystemUnderTest(utilityMock.Object);
sut.MethodToTest();


// Validate any parameters that are important, note these Verifications can occur in any
// order.
utilityMock.Verify(x => x.Operation2("2222"));
utilityMock.Verify(x => x.Operation1("1111"));
utilityMock.Verify(x => x.Operation3("3333"));

MockSequence를 사용하여 호출 순서 확인

Moq는 MockSequence 사용하여 호출 순서의 유효성 검사를 지원하지만 Strict MockSequence 사용할 때만 작동합니다. 그래서 다음과 같은 테스트 방법을 고려해보십시오.

public void MethodToTest()
{
    _utility.Operation1("1111");
    _utility.Operation2("2222");
    _utility.Operation3("3333");
}

다음과 같이 테스트 할 수 있습니다.

// Create the mock, not MockBehavior.Strict tells the mock how to behave
var utilityMock = new Mock<IUtility>(MockBehavior.Strict);

// Create the MockSequence to validate the call order
var sequence = new MockSequence();

// Create the expectations, notice that the Setup is called via InSequence
utilityMock.InSequence(sequence).Setup(x => x.Operation1(It.IsAny<string>()));
utilityMock.InSequence(sequence).Setup(x => x.Operation2(It.IsAny<string>()));
utilityMock.InSequence(sequence).Setup(x => x.Operation3(It.IsAny<string>()));

// Run the method to be tested
var sut = new SystemUnderTest(utilityMock.Object);
sut.MethodToTest();

// Verify any parameters that are cared about to the operation being orchestrated.
// Note that the Verify calls can be in any order
utilityMock.Verify(x => x.Operation2("2222"));
utilityMock.Verify(x => x.Operation1("1111"));
utilityMock.Verify(x => x.Operation3("3333"));

위의 예제는 기대를 설정할 때 It.IsAny<string> 을 사용합니다. 더 정확한 일치가 필요한 경우 관련 문자열 ( '1111', '2222', '3333')을 사용할 수있었습니다.

호출 순서가 잘못되었을 때보고 된 오류는 약간 오도 할 수 있습니다.

모의 행위로 인해 호출이 실패했습니다. Strict. 모의 모든 호출에는 해당 설정이 있어야합니다.

이것은 각 Setup 기대치가 이전 기대치가 만족 될 때까지 존재하지 않는 것처럼 처리되기 때문입니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow