Thomas Ardal

Entrepreneur and founder of elmah.io

Using Moq callbacks as Verify

One thing using Moq always bugged me. When needing to verify some method call, Moq provides a Verify-metod on the Mock object:

So, what’s wrong with this piece of code? In fact nothing (if you ask me). The “problem” is the error message if the test fails:

verify_error

Something fails! Moq is in fact pretty decent when it comes to error messages (compared to other mocking frameworks at least). Still, I don’t think the error is obvious here. It takes some time to spot, that the first parameter of the AMethodCall-method have a spelling mistake. What we really wanted here is to do an assert on each parameter using NUnit.

Even though callbacks in Moq isn’t ment to fix this, it solves the problem quite well. One might argue, that we compromise a bit with AAA, though. Our test using callbacks look like this:

A bit more complex, but our error message now tells us exactly what’s wrong:

callback_error

Show Comments