Language: EN

csharp-moq4

How to create mocks for testing in C# with Moq4

Moq4 is one of the most popular libraries for object mocking 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 often find that we depend on third-party objects. Using these objects prevents us from testing our code independently or unitarily.

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 limited and determined.

How to use Moq4

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

Install-Package Moq

Now, let’s suppose we have an interface

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

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);

With this, we have just made our ‘mock’ object that implements IMiClase, and it has a method DoSomething 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);
}

Of course, Moq4 has many options for masking any behavior. For example

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

In general, practically any behavior can be masked or “mocked”. In fact, it probably has options that you will never 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.

Moq4 is Open Source, and all its code is available on Moq · GitHub