Assertions in Moq Callbacks

I learned an important lesson today: do not assert inside of Moq callbacks. In the code below, even if the Assert.AreEqual fails, it will not cause the unit test to fail.

moqObj.Setup(m => m.Doit(It.IsAny<string>())).Callback<string>((s) => 
{
    Assert.AreEqual("foo", s);
});
// Insert test code that invokes `Doit`

You could use Verify instead, but it’s not always ideal, particularly when trying to step through the assertions while debugging tests. Instead, you can take this approach suggested by Thomas Ardal.

string actual = null;
moqObj.Setup(m => m.Doit(It.IsAny<string>())).Callback<string>((s) => 
{
    actual = s;
});
// Insert test code that invokes `Doit`
Assert.AreEqual("foo", actual);