Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

FakeItEasy Framework Jump Start

0.00/5 (No votes)
11 May 2015 9  
FakeItEasy Framework Jump Start

Introduction

I am writing this tip to demonstrate how to use FakeItEasy framework with C# in test Driven development environment. Using FakeItEasy, we can fake anything that could normally be overridden.

Background

I found FakeItEasy is the simplest fake framework to be used with .NET framework. FakeItEasy is a mocking framework for .NET that works with all types of fake objects (mocks, stubs) and is compatible with C# and VB.NET.

Currently, I am using FakeItEasy.1.25.2 version for this example with .NET 4.5 Framework.

Before proceeding with the code, please download FakeItEasy and Nunit from Nuget.

Steps to download FakeItEasy and Nunit from Nuget

  • Open the Package Manager Console: Tools → Library Package Manager → Package Manager Console
  • Execute Install-Package FakeItEasy
  • Execute Install-Package Nunit

Create Customer Class

In this example, I have created a public customer class with public virtual method GetCustomerName to return the customer name.

FakeItEasy is all about fake any object that are overridden like Interface, abstract, virtual. (//TODO)

In this example, I am using virtual keyword.

Without overridden capability, FakeItEasy will not be able to intercept the method and we will get an error message.

"Non virtual methods can not be intercepted". 

Our goal is to mock GetCustomerName and return the result as we like. I have skipped all wiring of connection database and returning the actual customer name because that is out of scope of this article.

C#
public class Customer
    {
        public virtual string GetCustomerName(int Id)
        {
            return "Select Customer";
        }
    }

Create Unit Test

The following code demonstrates how to fake GetCustomerName using FakeItEasy.

There are two simple steps to fake any object:

  1. Create Fake object

    Syntax : A.Fake<>()

  2. Configure a fake object behaviour

    Syntax : A.CallTo()

C#
[Test]
       public void Should_return_Customer_Name()
       {
       //Arrange
          <code> var fakeCustomerName = A.Fake<Customer>();</code>
       <code>    int customerId = 12; //Any number</code>

           //Act
           A.CallTo(() => fakeCustomerName.GetCustomerName(customerId)).Returns("Customer Name");

           //Assert
           Assert.AreEqual("Customer Name", fakeCustomerName.GetCustomerName(customerId));
       }

Conclusion

I found FakeItEasy to be the simplest fake framework for .NET. I find it very easy to use as compared to other mocking frameworks.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here