Total Downloads

2,598,780

Total Files

9,206

Latest Update

10

How to use Moq to ease unit testing in C#

Posted March 26, 2018 | Windows


We often need to write unit tests for code that accesses an external resource such as a database or a file file system. If such resources are not available, the only way to ensure that the tests can execute is by creating mock objects. In essence, by drawing on fake implementations of these underlying dependencies, you can test the interaction between the method being tested and its dependencies. Three of the most popular mocking frameworks for .Net developers are Rhino Mocks, Moq, and NMock.

Among these, Moq may be the most flexible and easy to use. The Moq framework provides an elegant way to set up, test, and verify mocks. This article presents a discussion of Moq and how it can be used to isolate units of code from their dependencies.

Getting started with Moq

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces. However, there are a few limitations you should be aware of. The classes to be mocked can’t be static or sealed, and the method being mocked should be marked as virtual. (Note there are workarounds to these restrictions. You could mock a static method by taking advantage of the adapter design pattern, for example.)

The first step in using Moq is to install it so that you can use it in your unit test project. You can download Moq from GitHub and add references as appropriate. However, I prefer installing Moq via NuGet because it is both easier and less likely to miss references. You can install Moq by using the following command at the NuGet command line.



Source link

')
ankara escort çankaya escort çankaya escort escort bayan çankaya istanbul rus escort eryaman escort ankara escort kızılay escort istanbul escort ankara escort ankara escort escort ankara istanbul rus Escort atasehir Escort beylikduzu Escort Ankara Escort malatya Escort kuşadası Escort gaziantep Escort izmir Escort