Using Moq to verify calls are made in the correct order

后端 未结 8 1694
青春惊慌失措
青春惊慌失措 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:45

    My scenario was methods without parameters:

    public interface IWriter
        {
        void WriteA ();
        void WriteB ();
        void WriteC ();
        }
    

    So I used Invocations property on the Mock to compare what was called:

    var writer = new Mock ();
    
    new SUT (writer.Object).Run ();
    
    Assert.Equal (
        writer.Invocations.Select (invocation => invocation.Method.Name),
        new[]
            {
            nameof (IWriter.WriteB),
            nameof (IWriter.WriteA),
            nameof (IWriter.WriteC),
            });
    

    You could also append the invocation.Arguments to check method calls with parameters.

    Also the failure message is more clear than just expected 1 but was 5:

        expected
    ["WriteB", "WriteA", "WriteC"]
        but was
    ["WriteA", "WriteB"]
    

提交回复
热议问题