How to replace the Moq framework with FakeItEasy in your unit-tests codebase

When working with unit tests in .NET, you might find yourself using the Moq framework to create mock objects. However, there are alternative frameworks like FakeItEasy that offer similar functionalities using a different approach. In this article, we’ll explore how to replace Moq with FakeItEasy, focusing on the following changes:

  1. Instantiating a New Mock
  2. Setting up / Mocking the response of a method
  3. Setting up properties
  4. Passing the Mock as a parameter to a class
  5. Replacing the Protected method of Moq
  6. Verifying method calls

1. Instantiating a New Mock

In Moq, you create a new mock object using the Mock<T> class:

var mock = new Mock<IMyService>();

In FakeItEasy, you create a new fake object using the A.Fake<T> method:

var fake = A.Fake<IMyService>();

2. Setting up / Mocking the response of a method

In Moq, you set up a method using the Setup method:

mock.Setup(x => x.MyMethod()).Returns("Hello, World!");

In FakeItEasy, you set up a method using the A.CallTo method:

A.CallTo(() => fake.MyMethod()).Returns("Hello, World!");

For defining the values of parameters of the mocked methods:

3. Setting Up Properties

In Moq, you set up properties using the SetupProperty method:

mock.SetupProperty(x => x.MyProperty, "InitialValue");

In FakeItEasy, you set up properties using the A.CallToSet method:

A.CallToSet(() => fake.MyProperty).To("InitialValue");

4. Passing the Mock as a parameter to a class

In Moq, you pass the mock object as a parameter using the .Object property:

var service = new MyService(mock.Object);

In FakeItEasy, you can pass the fake object directly without any additional properties:

var service = new MyService(fake);

5. Replacing the Protected method of Moq

In Moq, you can access protected members using the Protected method:

mock.Protected().Setup<string>("MyProtectedMethod").Returns("Hello, World!");

In FakeItEasy, there is no direct equivalent to Moq’s Protected. Instead, you can use the A.CallTo method with a lambda expression that accesses the protected member through a derived class:

var fake = A.Fake<MyService>();
A.CallTo(() => fake.MyProtectedMethod()).Returns("Hello, World!");

6. Verifying method calls

In Moq, you verify that a method was called using the Verify method:

mock.Verify(x => x.MyMethod(), Times.Once);

In FakeItEasy, you verify that a method was called using the A.CallTo method with the MustHaveHappened assertion:

A.CallTo(() => fake.MyMethod()).MustHaveHappenedOnceExactly();

Conclusion

Replacing Moq with FakeItEasy involves some changes in how you instantiate mocks, set up methods, pass mocks as parameters, and handle protected members. By following the examples provided, you can smoothly transition from Moq to FakeItEasy.

comments powered by Disqus