Skip to content

Instantly share code, notes, and snippets.

@jhgbrt
Created May 30, 2012 19:23
Show Gist options
  • Save jhgbrt/2838415 to your computer and use it in GitHub Desktop.
Save jhgbrt/2838415 to your computer and use it in GitHub Desktop.
Verifying method calls with Moq
[Test]
public void UsingMoqWithVerifications()
{
// Arrange
var dependency = new Mock<IDependency>();
// unfortunately there does not seem to be a simple way to set multiple return values with Moq...
var returnValues = new[] {7, 3};
var index = -1;
dependency.Setup(x => x.DoSomething(It.IsAny<SomeComplexType>(), It.IsAny<int>()))
.Returns(() => returnValues[++index]);
// Act
var systemUnderTest = new SystemUnderTest(dependency.Object);
var returned = systemUnderTest.MethodUnderTest("MyData", 1234);
// Assert
// (note: it would be even better to move the asserts to seperate tests and put the Arrange/Act part in a TextFixtureSetUp)
Assert.AreEqual(10, returned);
// Verify lets us check the arguments of the expected method calls using lambda expressions through the "It." class
dependency.Verify(
x => x.DoSomething(It.Is((SomeComplexType arg1) => arg1.stringData == "Sending MyData"), 1111),
Times.Once());
dependency.Verify(
x => x.DoSomething(It.Is((SomeComplexType arg1) => arg1.stringData == "Sending 1234"), 2222),
Times.Once());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment