In this article, we’ll learn about the Autofac FakeItEasy Package, its features, benefits, and how to get started. We’ll learn how to use the package to create unit tests for our applications.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

What Is Autofac?

Autofac is a dependency injection container for .NET. The library enables us to automatically resolve dependencies for our classes, which in turn simplifies our code. This way we have more modular and reusable code across our applications. Be sure to check out our introductory article for a deep dive into the Autofac package.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

What Is FakeItEasy?

FakeItEasy is a mocking framework for .NET. It allows us to create fake objects or mocks of real objects. This can be useful for unit testing, as it allows us to isolate our code from its dependencies and test it.

What Is the Autofac FakeItEasy Package?

The Autofac FakeItEasy Package is a NuGet package that integrates Autofac and FakeItEasy. It allows us to automatically create fake dependencies for our unit tests using an Autofac container.

To install the NuGet package, we run the .NET CLI command: dotnet add package FakeItEasy

Why Use Autofac and FakeItEasy Packages Together?

The combination of Autofac and FakeItEasy offers a great solution for writing tests. Autofac automates dependency injection, while FakeItEasy mocks the functionality under test. FakeItEasy provides a fluent API for creating mock objects, making it easy to decouple our code from external dependencies and focus on the core functionality being tested.

Also, by configuring options for our mock objects, we can return specific values, throw exceptions, or track interactions, giving us fine-grained control over our tests.

By mocking dependencies, the library enables us to test different pieces of our applications independently. This makes our code easy to read and maintain. Also, since we’re not calling any external systems, mocks help speed up our tests.

These benefits are achieved because Autofac and FakeItEasy work together to automate the creation and configuration of fake dependencies. This frees us up to focus on writing unit tests that test the behavior of our code, rather than worrying about how to create and configure its dependencies.

Overall, using Autofac and FakeItEasy together is a great way to improve the quality and efficiency of unit testing. Both libraries are open-source and have active communities around them. These communities guarantee continuous development and support.

Let’s look at some of the features of the Autofac FakeItEasy package.

Features of the Autofac FakeItEasy Package

First, let’s create an abstraction IEmployeeService: 

public interface IEmployeeService
{
    Employee GetById(long id);
    List<Employee> GetAll();
}

Then, let’s add a class in which we inject the dependency:

public class EmployeeService
{
    private readonly IEmployeeService _employeeService;

    public EmployeeService(IEmployeeService employeeService)
    {
        _employeeService = employeeService;
    }

    public Employee GetEmployeeById(long id)
    {
        return _employeeService.GetById(id);
    }

    public List<Employee> GetAllEmployees()
    {
        return _employeeService.GetAll();
    }
}

In this class, we inject the IEmployeeService abstraction as a dependency and then implement the respective methods.

With the setup done, let’s look at some of the features of the Autofac FakeItEasy package.

Automatic Creation of Fake Dependencies

The Autofac FakeItEasy package automatically creates fake dependencies of the services under test. We can create a fake IEmployeeService dependency for the EmployeeService implementation:

var fakeEmployeeService = A.Fake<IEmployeeService>();

This way we don’t have to manually  inject the IEmployeeService interface in the test class.

Having set up the fake service, we can mock the first test:

A.CallTo(() => fakeEmployeeService.GetById(1)).Returns(new Employee
{
    Id = 1,
    Name = "Jane Doe",
    Title = "Mrs"
});

Here, we call the GetById() method of the fakeEmployeeService using the CallTo() method of the Autofac library.

Support for Array Types, IEnumerable<T> Types, and Concrete Types

Autofac has the AnyConcreteTypeNotAlreadyRegisteredSource() (ACTNARS) method which provides a mechanism to resolve any concrete type from the Autofac container, regardless of whether it has been explicitly registered. This behavior can be particularly useful when dealing with IEnumerable types, as it allows us to dynamically resolve collections of unregistered types.

This way, the library supports the inversion of control SOLID principle:

var employee1 = new Employee { Id = 1, Name = "John Doe" };
var employee2 = new Employee { Id = 2, Name = "Jane Doe" };

var expectedEmployees = new List<Employee> { employee1, employee2 };

var fakeEmployeeService = A.Fake<IEmployeeService>();
A.CallTo(() => fakeEmployeeService.GetAll()).Returns(expectedEmployees);

var builder = new ContainerBuilder();
builder.RegisterInstance(fakeEmployeeService);
builder.RegisterType<EmployeeService>();
builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());

var container = builder.Build();
using var scope = container.BeginLifetimeScope();

var employeeService = scope.Resolve<EmployeeService>();

var employees = employeeService.GetAllEmployees();

Assert.Equal(expectedEmployees, employees);

Here, we  utilize the AnyConcreteTypeNotAlreadyRegisteredSource() method to ensure that concrete implementations of IEnumerable types are automatically resolved, enabling the GetAllEmployees() method to receive actual instances of IEnumerable<Employee> rather than fake collections.

The BeginLifetimeScope() method creates a new nested lifetime scope for each call to the GetAllEmployees() method. This ensures that the GetAllEmployees() method returns unique results for each call, preventing any potential conflicts or side effects from previous calls.

Configuring the Behavior of Dependencies by Specifying Options

Using FakeItEasy, we can easily dictate what happens when certain methods are called or properties are accessed. We can specify return values, set up property behaviors, or define expectations for method calls:

var employeeId = 1;
var expectedEmployee = new Employee
{
    Id = employeeId,
    Name = "Jane Doe",
    Title = "Mrs"
};

var fakeEmployeeService = A.Fake<IEmployeeService>();

A.CallTo(() => fakeEmployeeService.GetById(employeeId)).Returns(expectedEmployee);

We define expectedEmployee and then specify that the GetById() method call should return the defined value.

Also, we can define whether we want our mocks to be more stringent by configuring our mocks to be strict:

var fakeEmployeeService = A.Fake<IEmployeeService>(options => options.Strict());

This way, we create a mock with strict behavior such that any unconfigured calls will throw exceptions. Also, by configuring strict behavior, we can verify that the application calls all the expected methods.

Conclusion

The Autofac FakeItEasy package offers a great solution for testing our .NET applications.

In this article, we’ve only covered the introductory part of it. We’ve learned how it automates dependency injection and mocking of dependencies reducing boilerplate code we would otherwise have.

We’ve also learned how we can use it to fine-tune our tests and have more control of our tests. On top of that, it integrates well with other .NET testing libraries making it easy to work with, for both new and seasoned .NET developers.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!