Visual Studio snippets for Moq

These days, I use Moq a lot. There are things I like and I don’t like about creating fakes with Moq. But it’s simple and easy to use.

I use the same four Moq methods all the time. Setup, ReturnAsync, ThrowsAsync and Verify. That’s all you need. I decided to create snippets inside Visual Studio to avoid typing the same method names every time. These are the snippets I use.

Create a Mock with Moq

Use mn to create a Mock. It expands to var mock = new Mock<>();.

mn to create a Mock
Use mn to create a Mock

Setup and Return

With a mock instance, use mr to Setup a method to Return something.

mr to Setup/Return
Use mr to Setup/Return

Setup and ThrowsException

If you want to throw an exception from your mock, use mt.

mt to Setup/ThrowsException
Use mt to Setup/ThrowsException

Also, you can use mra and mta for the asynchronous version of Return and ThrowsException respectively.

If you want to use the same snippets I use, download the snippets file from VSMoqSnippets repository.

To load snippets into Visual Studio, from the “Tools” menu, choose “Code Snippets Manager” and import the snippets file.

canro91/VSMoqSnippets - GitHub

Voilà! Those are the snippets I use for Moq. Check my Visual Studio setup for more settings and extensions. Do you want to learn more about fakes? Read what are fakes in unit testing and these tips for better stubs and mocks.

Happy coding!