65.9K
CodeProject is changing. Read more.
Home

FakeItEasy Framework Jump Start

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (2 votes)

May 11, 2015

CPOL

1 min read

viewsIcon

16751

downloadIcon

1

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.

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

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

            //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.