Visual Studio snippets for Moq
22 Feb 2021 #productivity #visualstudio #showdevThese 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<>();
.
Setup and Return
With a mock instance, use mr
to Setup
a method to Return
something.
Setup and ThrowsException
If you want to throw an exception from your mock, use mt
.
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.
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!