csharp-moq4

How to create mocks for testing in C# with Moq4

  • 2 min

Moq4 is one of the most popular libraries for mocking objects in .NET.

Mocked objects, or as we commonly call them “mocks”, are fictitious objects that we generally use during the testing phase.

When performing unit tests on code, we will often find that we depend on third-party objects. Using these objects prevents us from testing our code independently or in a unit.

The usual solution is to create a fictitious object that we will use in our test, which simulates the behavior of the real object, but in a limited and defined way.

How to use Moq4

We can easily add the library to a .NET project through the corresponding Nuget package.

Install-Package Moq
Copied!

Now, suppose we have an interface

public interface IMiClase
{
    string Name { get; set; }
    int Value { get; set; }
    bool DoSomething(string value);
    int GetValue();
Copied!

We can create a Mock of IMiClase by doing

var mock = new Mock<IMiClase>();
mock.Setup(x => x.DoSomething("something")).Returns(true);
mock.Setup(x => x.GetValue()).Returns(5);
Copied!

With this, we have just made our ‘mock’ object that implements IMiClase, and which has a DoSomething method that, when called with the parameter ‘something’, returns true.

Now we can use this object in our Tests, without having a “Real” object that implements IMiClase, but something that simulates it (a Mock).

[Fact]
public void TestMethod()
{
    var mock = new Mock<IMiClase>();
    mock.Setup(x => x.DoSomething("something")).Returns(true);
    mock.Setup(x => x.GetValue()).Returns(5);

    var result = myClass.GetValue();
    Assert.Equal(5, result);
}
Copied!

Of course, Moq4 has a huge number of options for mocking any behavior. For example

  • Properties
  • Synchronous or asynchronous methods
  • Parameters passed to methods
  • Inheritance
  • Events and callbacks

In general, practically any behavior can be mocked. In fact, it probably has options you will never even use.

You can see all the available options in the project documentation, especially in the QuickStart section which has a lot of examples on how to use Moq4.