Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq expectations on the same method twice in a row

Tags:

c#

testing

moq

I am trying to set up exceptions for a method that is called twice in a row with different parameters. Like this:

  var adapter = new Mock<IKeyAdapter>();
  adapter.Setup(x => x.ImportKey(It.IsAny<Guid>(), key, It.IsAny<string>(), publicTicket)).Returns(Guid.NewGuid());
  adapter.Setup(x => x.ImportKey(It.IsAny<Guid>(), key, It.IsAny<string>(), privateTicket)).Returns(Guid.Empty);

I wan't the first to pass and the second to fail. Currently it seems that the second setup overwrites the first.

Is this possible with Moq?

like image 965
Lewis Jubb Avatar asked Mar 15 '11 12:03

Lewis Jubb


1 Answers

You are correct that the second expectation is overwriting the first. This appears to be a current limitation. Some workarounds have been devised as follows:

  • Moq Sequences which can obtained here at github.
  • Overloading IExpect.Returns to take an expression rather than a value as described here, and elaborated on here and here.
like image 196
Matt Avatar answered Oct 22 '22 21:10

Matt