Using Moq to verify calls are made in the correct order

后端 未结 8 1699
青春惊慌失措
青春惊慌失措 2020-12-01 10:00

I need to test the following method:

CreateOutput(IWriter writer)
{
    writer.Write(type);
    writer.Write(id);
    writer.Write(sender);

    // many more         


        
8条回答
  •  星月不相逢
    2020-12-01 10:58

    Recently, I put together two features for Moq: VerifyInSequence() and VerifyNotInSequence(). They work even with Loose Mocks. However, these are only available in a moq repository fork:

    https://github.com/grzesiek-galezowski/moq4

    and await more comments and testing before deciding on whether they can be included in official moq releaase. However, nothing prevents you from downloading the source as ZIP, building it into a dll and giving it a try. Using these features, the sequence verification you need could be written as such:

    var mockWriter = new Mock() { CallSequence = new LooseSequence() };
    
    //perform the necessary calls
    
    mockWriter.VerifyInSequence(x => x.Write(expectedType));
    mockWriter.VerifyInSequence(x => x.Write(expectedId));
    mockWriter.VerifyInSequence(x => x.Write(expectedSender));
    

    (note that you can use two other sequences, depending on your needs. Loose sequence will allow any calls between the ones you want to verify. StrictSequence will not allow this and StrictAnytimeSequence is like StrictSequence (no method calls between verified calls), but allows the sequence to be preceeded by any number of arbitrary calls.

    If you decide to give this experimental feature a try, please comment with your thoughts on: https://github.com/Moq/moq4/issues/21

    Thanks!

提交回复
热议问题