When using MOQ 4, you can use SetupSequence, otherwise it can be done using lambda
Using SetupSequence is pretty clear.
Using lambda is not too dirty. The important point is not that the return value is set when the installation is declared . If you just used
mockFoo.Setup(mk => mk.Bar()).Returns(pieces[pieceIdx++]);
the setting will always return parts [0]. Using lambda, evaluation is deferred until Bar () is called.
public interface IFoo { string Bar(); } public class Snafu { private IFoo _foo; public Snafu(IFoo foo) { _foo = foo; } public string GetGreeting() { return string.Format("{0} {1}", _foo.Bar(), _foo.Bar()); } } [TestMethod] public void UsingSequences() { var mockFoo = new Mock<IFoo>(); mockFoo.SetupSequence(mk => mk.Bar()).Returns("Hello").Returns("World"); var snafu = new Snafu(mockFoo.Object); Assert.AreEqual("Hello World", snafu.GetGreeting()); } [TestMethod] public void NotUsingSequences() { var pieces = new[] { "Hello", "World" }; var pieceIdx = 0; var mockFoo = new Mock<IFoo>(); mockFoo.Setup(mk => mk.Bar()).Returns(()=>pieces[pieceIdx++]); var snafu = new Snafu(mockFoo.Object); Assert.AreEqual("Hello World", snafu.GetGreeting()); }
AlanT source share