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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With