C# FakeItEasy
last modified October 18, 2026
In this article we show how to do mocking in C# using the FakeItEasy library.
Faking is replacing external dependencies with fakes or test doubles. These classes or components simulate successful or failed operations in unit testing.
Fakes are used primarily because the external dependencies might currently not be available for testing, their usage is slow or costly (a database, a mail server, a web service), or because we want to simulate situations that are hard to produce, such as errors. A fake also records the calls it receives, so a test can verify how the code under test used its dependency.
FakeItEasy is an easy mocking library for .NET. A fake is created with
A.Fake<T>() for an interface or a class with overridable members;
the behaviour is configured with A.CallTo(...).
$ dotnet new mstest -n Shop $ cd Shop $ dotnet add package FakeItEasy
In this article we use the MSTest testing framework (version 4 or newer, from the
MSTest package; the template references it already). The code under test
and the tests are in one project, to keep the layout simple.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FakeItEasy" Version="9.0.1" />
<PackageReference Include="MSTest" Version="4.0.2" />
</ItemGroup>
<ItemGroup>
<Using Include="Microsoft.VisualStudio.TestTools.UnitTesting" />
</ItemGroup>
</Project>
This is the project file of the test project.
The code under test
The first version of this tutorial created a fake from an interface and then tested
that the fake returned what it had been told to return. That proves nothing about
our code. A useful test fakes the dependencies of a class and tests the
class itself. Our class is an OrderService that saves orders to a
repository and sends a confirmation by e-mail.
namespace Shop.Models; public record Order(int Id, string Customer, decimal Amount);
The Order is a simple record.
using Shop.Models;
namespace Shop.Services;
public interface IOrderRepository
{
Order? Find(int id);
void Save(Order order);
int Count { get; }
Task<IReadOnlyList<Order>> GetByCustomerAsync(string customer);
}
The IOrderRepository abstracts the storage. It has methods, a property,
and an asynchronous method.
namespace Shop.Services;
public interface IEmailSender
{
void Send(string to, string subject, string body);
bool TryValidate(string address, out string normalized);
}
The IEmailSender abstracts the mail server. The
TryValidate method has an out parameter.
using Shop.Models;
namespace Shop.Services;
public class OrderService(IOrderRepository repository, IEmailSender mailer, TimeProvider time)
{
public Order PlaceOrder(int id, string customer, decimal amount)
{
if (amount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(amount), "The amount must be positive.");
}
if (repository.Find(id) is not null)
{
throw new InvalidOperationException($"Order {id} already exists.");
}
var order = new Order(id, customer, amount);
repository.Save(order);
if (mailer.TryValidate(customer, out var address))
{
var day = time.GetUtcNow().ToString("yyyy-MM-dd");
mailer.Send(address, "Order confirmed", $"Order {id} for {amount:F2} was placed on {day}.");
}
return order;
}
public async Task<decimal> TotalForAsync(string customer)
{
var orders = await repository.GetByCustomerAsync(customer);
return orders.Sum(o => o.Amount);
}
}
The OrderService is the class we test. It receives its dependencies in
the constructor, which is what makes it testable: a test passes fakes instead of the
real database and mail server. Even the clock is a dependency, the
TimeProvider class (see the date and
time tutorial), so the test can fix the date in the message.
C# FakeItEasy simple example
In the first test class, we look at how a fake behaves when it is created and how we change its behaviour.
using FakeItEasy;
using Shop.Models;
using Shop.Services;
namespace Shop.Tests;
[TestClass]
public class SimpleFakeTests
{
[TestMethod]
public void UnconfiguredFakeReturnsDefaults()
{
var repository = A.Fake<IOrderRepository>();
Assert.AreEqual(0, repository.Count); // a value type: its default
Assert.IsNotNull(repository.Find(1)); // a class that can be faked: a dummy object
Assert.IsFalse(repository.GetByCustomerAsync("x").Result.Any()); // an empty collection in a completed task
}
[TestMethod]
public void ConfiguredFakeReturnsTheValue()
{
var repository = A.Fake<IOrderRepository>();
var order = new Order(1, "john@example.com", 10m);
A.CallTo(() => repository.Find(1)).Returns(order);
A.CallTo(() => repository.Count).Returns(42);
Assert.AreEqual(order, repository.Find(1));
Assert.AreNotEqual(order, repository.Find(2)); // other arguments get the default: a dummy
Assert.AreEqual(42, repository.Count);
}
}
var repository = A.Fake<IOrderRepository>();
We create a fake from the IOrderRepository interface. FakeItEasy
generates a class that implements the interface at run time.
Assert.AreEqual(0, repository.Count);
Assert.IsNotNull(repository.Find(1));
Assert.IsFalse(repository.GetByCustomerAsync("x").Result.Any());
An unconfigured fake does not throw; it returns sensible default values. For a value
type, it is the default (0 for Count). For a type that can be faked
or created, such as our Order class, it returns a dummy object, not
null, even though the return type is Order?. A string is
empty, a collection is empty, and a method returning a task returns a completed task
with the default value. This is convenient, but it also means that a missing
configuration may go unnoticed. Strict fakes, shown below, change this.
A.CallTo(() => repository.Find(1)).Returns(order); A.CallTo(() => repository.Count).Returns(42);
A.CallTo takes a lambda with the call we configure, and
Returns sets the value. Properties are configured in the same way.
Calls with other arguments are not affected; Find(2) still returns a
dummy.
C# FakeItEasy testing a class
Now we test the OrderService with fake dependencies. The
TestInitialize method creates new fakes and a new service before each
test, so the tests do not influence each other.
using FakeItEasy;
using Shop.Models;
using Shop.Services;
namespace Shop.Tests;
[TestClass]
public class OrderServiceTests
{
private IOrderRepository repository = null!;
private IEmailSender mailer = null!;
private OrderService service = null!;
[TestInitialize]
public void Setup()
{
repository = A.Fake<IOrderRepository>();
mailer = A.Fake<IEmailSender>();
// by default no order exists; without this line the fake would return a dummy Order
A.CallTo(() => repository.Find(A<int>._)).Returns(null);
var time = new FakeClock(new DateTimeOffset(2026, 10, 18, 9, 0, 0, TimeSpan.Zero));
service = new OrderService(repository, mailer, time);
}
[TestMethod]
public void PlaceOrder_SavesTheOrder()
{
var order = service.PlaceOrder(1, "john@example.com", 25m);
Assert.AreEqual(new Order(1, "john@example.com", 25m), order);
A.CallTo(() => repository.Save(order)).MustHaveHappenedOnceExactly();
}
[TestMethod]
public void PlaceOrder_SendsConfirmationToValidAddress()
{
string normalized = "john@example.com";
A.CallTo(() => mailer.TryValidate("John@Example.com", out normalized)).Returns(true);
service.PlaceOrder(1, "John@Example.com", 25m);
A.CallTo(() => mailer.Send("john@example.com", "Order confirmed", "Order 1 for 25.00 was placed on 2026-10-18."))
.MustHaveHappenedOnceExactly();
}
[TestMethod]
public void PlaceOrder_DoesNotSendMailToInvalidAddress()
{
// the unconfigured TryValidate returns false
service.PlaceOrder(1, "not an address", 25m);
A.CallTo(() => mailer.Send(A<string>._, A<string>._, A<string>._)).MustNotHaveHappened();
A.CallTo(() => repository.Save(A<Order>._)).MustHaveHappenedOnceExactly();
}
[TestMethod]
public void PlaceOrder_RejectsDuplicates()
{
A.CallTo(() => repository.Find(7)).Returns(new Order(7, "x", 1m));
var ex = Assert.ThrowsExactly<InvalidOperationException>(() => service.PlaceOrder(7, "jane@example.com", 5m));
Assert.AreEqual("Order 7 already exists.", ex.Message);
A.CallTo(() => repository.Save(A<Order>._)).MustNotHaveHappened();
}
[TestMethod]
[DataRow(0)]
[DataRow(-5)]
public void PlaceOrder_RejectsNonPositiveAmounts(int amount)
{
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => service.PlaceOrder(1, "a@b.c", amount));
A.CallTo(repository).MustNotHaveHappened();
}
[TestMethod]
public void PlaceOrder_SavesBeforeSendingMail()
{
string ignored;
A.CallTo(() => mailer.TryValidate(A<string>._, out ignored)).Returns(true);
service.PlaceOrder(1, "a@b.c", 5m);
A.CallTo(() => repository.Save(A<Order>._)).MustHaveHappened()
.Then(A.CallTo(() => mailer.Send(A<string>._, A<string>._, A<string>._)).MustHaveHappened());
}
}
class FakeClock(DateTimeOffset now) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => now;
}
A.CallTo(() => repository.Find(A<int>._)).Returns(null);
In the setup, we tell the repository that no order exists. Without it, the fake
would return a dummy order, and the service would report a duplicate. The expression
A<int>._ is a shortcut for A<int>.Ignored and
matches any argument.
A.CallTo(() => repository.Save(order)).MustHaveHappenedOnceExactly();
This is the verification part. After running the code under test, we assert that the
dependency was called as expected. MustHaveHappenedOnceExactly demands
exactly one call; there are also MustHaveHappened(),
MustNotHaveHappened(), and MustHaveHappened(n, Times.Exactly).
Arguments are compared with Equals, so the record Order
matches by value.
string normalized = "john@example.com";
A.CallTo(() => mailer.TryValidate("John@Example.com", out normalized)).Returns(true);
For a method with an out parameter, the argument must be a variable.
FakeItEasy matches the call, and the value of the variable becomes the value of the
out parameter. The unconfigured TryValidate returns false,
which the next test uses for an invalid address.
A.CallTo(() => mailer.Send(A<string>._, A<string>._, A<string>._)).MustNotHaveHappened();
Verifying that something did not happen is just as important. Here, no
mail is sent to an invalid address. A.CallTo(fake).MustNotHaveHappened()
without a lambda means that no call at all was made to the fake, which would
be too strict here, because the service did call TryValidate.
var ex = Assert.ThrowsExactly<InvalidOperationException>(() => service.PlaceOrder(7, "jane@example.com", 5m));
We test the failure paths too. When the repository already has the order, the
service throws, and nothing must be saved. Assert.ThrowsExactly is the
MSTest 4 assertion for exceptions; it returns the exception for further checks.
A.CallTo(() => repository.Save(A<Order>._)).MustHaveHappened()
.Then(A.CallTo(() => mailer.Send(A<string>._, A<string>._, A<string>._)).MustHaveHappened());
The Then method verifies the order of calls, also across
different fakes: the order is saved first and the mail is sent afterward.
$ dotnet test ... Passed! - Failed: 0, Passed: 15, Skipped: 0, Total: 15
When an expectation fails, the message lists the actual calls, which makes the problem easy to see:
FakeItEasy.ExpectationException:
Assertion failed for the following call:
Shop.Services.IOrderRepository.Save(order: Order { Id = 2, Customer = y, Amount = 5 })
Expected to find it once or more but didn't find it among the calls:
1: Shop.Services.IOrderRepository.Save(order: Order { Id = 1, Customer = x, Amount = 5 })
C# FakeItEasy advanced features
The next test class shows more of the library: argument constraints, computed results, sequences, exceptions, callbacks, asynchronous methods, out parameters, strict fakes, and dummies.
using FakeItEasy;
using Shop.Models;
using Shop.Services;
namespace Shop.Tests;
[TestClass]
public class AdvancedFakeTests
{
[TestMethod]
public void ArgumentConstraints()
{
var repository = A.Fake<IOrderRepository>();
A.CallTo(() => repository.Find(A<int>.That.Matches(id => id > 100)))
.Returns(new Order(101, "big", 1m));
Assert.AreNotEqual("big", repository.Find(5)!.Customer); // the dummy for other ids
Assert.AreEqual("big", repository.Find(500)!.Customer);
A.CallTo(() => repository.Find(A<int>.Ignored)).MustHaveHappened(2, Times.Exactly);
A.CallTo(() => repository.Find(A<int>.That.IsGreaterThan(100))).MustHaveHappenedOnceExactly();
}
[TestMethod]
public void ReturnsComputedValuesAndSequences()
{
var repository = A.Fake<IOrderRepository>();
A.CallTo(() => repository.Find(A<int>._))
.ReturnsLazily((int id) => new Order(id, $"customer{id}", id * 10m));
Assert.AreEqual(30m, repository.Find(3)!.Amount);
A.CallTo(() => repository.Count).ReturnsNextFromSequence(1, 2, 3);
Assert.AreEqual(1, repository.Count);
Assert.AreEqual(2, repository.Count);
Assert.AreEqual(3, repository.Count);
Assert.AreEqual(0, repository.Count); // the sequence is exhausted: back to the default
}
[TestMethod]
public void ThrowsAndInvokes()
{
var repository = A.Fake<IOrderRepository>();
var saved = new List<string>();
A.CallTo(() => repository.Save(A<Order>.That.Matches(o => o.Amount > 1000)))
.Throws(new InvalidOperationException("limit exceeded"));
A.CallTo(() => repository.Save(A<Order>.That.Matches(o => o.Amount <= 1000)))
.Invokes((Order o) => saved.Add(o.Customer));
repository.Save(new Order(1, "small", 10m));
Assert.ThrowsExactly<InvalidOperationException>(() => repository.Save(new Order(2, "huge", 5000m)));
CollectionAssert.AreEqual(new[] { "small" }, saved);
}
[TestMethod]
public async Task AsyncMethods()
{
var repository = A.Fake<IOrderRepository>();
var orders = new List<Order> { new(1, "john", 10m), new(2, "john", 15.5m) };
A.CallTo(() => repository.GetByCustomerAsync("john")).Returns(orders); // wrapped in a completed task
var service = new OrderService(repository, A.Fake<IEmailSender>(), TimeProvider.System);
Assert.AreEqual(25.5m, await service.TotalForAsync("john"));
Assert.AreEqual(0m, await service.TotalForAsync("nobody")); // the default: an empty list
}
[TestMethod]
public void OutParametersAndStrictFakes()
{
var mailer = A.Fake<IEmailSender>();
string outValue;
A.CallTo(() => mailer.TryValidate("JOHN@EXAMPLE.COM", out outValue))
.Returns(true)
.AssignsOutAndRefParameters("john@example.com");
Assert.IsTrue(mailer.TryValidate("JOHN@EXAMPLE.COM", out var normalized));
Assert.AreEqual("john@example.com", normalized);
// a strict fake throws for every call that has not been configured
var strict = A.Fake<IOrderRepository>(o => o.Strict());
A.CallTo(() => strict.Count).Returns(3);
Assert.AreEqual(3, strict.Count);
Assert.ThrowsExactly<ExpectationException>(() => strict.Find(1));
}
[TestMethod]
public void CapturingArgumentsAndDummies()
{
var mailer = A.Fake<IEmailSender>();
var subjects = new List<string>();
A.CallTo(() => mailer.Send(A<string>._, A<string>.Ignored, A<string>._))
.Invokes((string to, string subject, string body) => subjects.Add(subject));
mailer.Send("a@b.c", "first", "...");
mailer.Send("a@b.c", "second", "...");
CollectionAssert.AreEqual(new[] { "first", "second" }, subjects);
// dummies and collections of fakes
Order dummy = A.Dummy<Order>();
IList<IOrderRepository> repositories = A.CollectionOfFake<IOrderRepository>(3);
Assert.IsNotNull(dummy);
Assert.HasCount(3, repositories);
}
}
A.CallTo(() => repository.Find(A<int>.That.Matches(id => id > 100)))
.Returns(new Order(101, "big", 1m));
A<T>.That adds a constraint to the argument. The configuration
applies only when the argument satisfies it; here, ids greater than 100. Besides
Matches, there are ready-made constraints such as
IsGreaterThan, IsNull, StartsWith, and
IsSameAs, and the constraints can also be used in the verification
(MustHaveHappened).
A.CallTo(() => repository.Find(A<int>._))
.ReturnsLazily((int id) => new Order(id, $"customer{id}", id * 10m));
ReturnsLazily computes the result from the arguments of the call, at the
time of the call. Returns evaluates the value once, when we configure.
A.CallTo(() => repository.Count).ReturnsNextFromSequence(1, 2, 3);
A sequence returns different values on consecutive calls. After the sequence is exhausted, the default value is returned. This is useful to simulate state changes.
A.CallTo(() => repository.Save(A<Order>.That.Matches(o => o.Amount > 1000)))
.Throws(new InvalidOperationException("limit exceeded"));
A.CallTo(() => repository.Save(A<Order>.That.Matches(o => o.Amount <= 1000)))
.Invokes((Order o) => saved.Add(o.Customer));
Throws simulates a failure of the dependency, which is hard to produce
with the real one. Invokes runs our code when the method is called and
receives the arguments; here it collects them. A method that returns
void can be configured only in this way, or with
DoesNothing.
A.CallTo(() => repository.GetByCustomerAsync("john")).Returns(orders);
For a method that returns Task<T>, Returns accepts
the plain value and wraps it in a completed task. The test method is
async Task and awaits the service. The unconfigured call for another
customer returns a completed task with an empty collection, so the total is zero.
A.CallTo(() => mailer.TryValidate("JOHN@EXAMPLE.COM", out outValue))
.Returns(true)
.AssignsOutAndRefParameters("john@example.com");
AssignsOutAndRefParameters sets the values of out and ref parameters.
var strict = A.Fake<IOrderRepository>(o => o.Strict());
A strict fake throws an ExpectationException for every call that has not
been configured, instead of returning defaults. Use it when we want to know exactly
which members the code under test touches. Because of the surprises it brings,
strict fakes are the exception and not the rule.
Order dummy = A.Dummy<Order>(); IList<IOrderRepository> repositories = A.CollectionOfFake<IOrderRepository>(3);
A.Dummy<T>() creates an object that just fills a required argument
and whose content does not matter. A.CollectionOfFake<T>(n)
creates a list of n fakes (and CollectionOfDummy a list of dummies).
FakeItEasy limitations
FakeItEasy can fake interfaces, abstract classes, and non-sealed classes, but only
members that are virtual or abstract. It cannot fake static
methods, sealed classes, or non-virtual members. This is one more reason to program
against interfaces and to pass dependencies in the constructor. If the code uses
DateTime.Now or File directly, wrap them in an interface
or use abstractions such as TimeProvider.
Faking everything also makes tests brittle: they then verify the implementation
(which methods were called in which order) instead of the behaviour. Prefer
asserting on results and use MustHaveHappened for the interactions that
are the point of the test, such as "a mail was sent".
Source
In this article we have replaced the dependencies of a class with test doubles in C# with FakeItEasy.
Author
List all C# tutorials.