Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq SetupSequence doesn't work

I try to use the SetupSequence method of the Moq 4.5 framework.

Class that should be mocked:

public class OutputManager {
    public virtual string WriteMessage(string message) {
    // write a message
    }
}

Mock:

var outputManagerMock = new Mock<OutputManager>();
var writeMessageCalls = 0;
var currentMessage = String.Empty;

outputManagerMock.Setup(o => o.WriteMessage(It.IsAny<string>())).Callback((string m) => {
    writeMessageCalls++;
    message = m;
});

This code works fine. But I'd like having a different setup for each call of the WriteMessage method. Well, I use SetupSequence instead of Setup:

var outputManagerMock = new Mock<OutputManager>();
var writeMessageCalls = 0;
var firstMessage = String.Empty;
var secondMessage = String.Empty;

outputManagerMock.SetupSequence(o => o.WriteMessage(It.IsAny<string>()))
.Callback((string m) => {
    writeMessageCalls++;
    firstMessage = m;
}).Callback((string m) => {
    writeMessageCalls++;
    secondMessage = m;
});

Then I've got the error:

Error CS0411 The type arguments for method
'SequenceExtensions.SetupSequence<TMock, TResult>(Mock<TMock>, Expression<Func<TMock, TResult>>)' cannot be inferred from the usage.
Try specifying the type arguments explicitly.

I've found the possible solution here - SetupSequence in Moq. But it looks like a workaround.

like image 219
Sergey Avatar asked Sep 16 '25 18:09

Sergey


1 Answers

SetupSequence is used to setup a sequence of returns based on the number of the attempt to use the method that is being set up. An example based on your code which demonstrates what I am talking about :

outputManagerMock.SetupSequence(o => o.WriteMessage(It.IsAny<string>()))
.Returns("Hello for the first attempt!")
.Returns("This is the second attempt to access me!")
.Throws(new Exception());
like image 159
Akram Qalalwa Avatar answered Sep 18 '25 10:09

Akram Qalalwa