FakeItEasy and verifying method parameters

By | May 16, 2015

How about checking if the method was called with right parameters as a part of your unit tests ? You can do it in many ways.

Using FakeItEasy, it is easy to verify that the expected parameters were used to make the function call.

FakeItEasy method parameter verification is very flexible. It allows you to check the value of a particular parameter amongst the many parameters which the function might take effectively ignoring other parameters.

Now I have cooked up a very contrived example. Please do not judge me on this.

using System;

namespace DemoFakeItEasy
{
    public struct WorkOrder
    {
        public int workOrderId;
        public string address;

        public WorkOrder(int workOrderId, string address)
        {
            this.workOrderId = workOrderId;
            this.address = address;
        }
    }

    public class WorkOrderProcess
    {
        WorkOrder workOrder;

        public virtual void TestThisMethod(string productName, WorkOrder workOrder)
        { }

        public WorkOrderProcess(string productName, int workOrderNumber, string address)
        {
            workOrder = new WorkOrder(workOrderNumber, address);
            TestThisMethod(productName, workOrder);
        }
    }
}

 

The method “TestThisMethod” is the method we want to check. We want to verify that it was called with right parameters. Now you might question the wisdom of doing this but then this is just a demo.

Now the test code:

using System;
using FakeItEasy;
using Xunit;

namespace DemoFakeItEasy
{
    public class Tests
    {
        [Fact]
        public void Test_Method_Params()
        {
            var fakeWorkOrder = A.Fake<WorkOrderProcess>(x => x.WithArgumentsForConstructor(() => new WorkOrderProcess("IceCream", 23, "NewYork")));

            A.CallTo(fakeWorkOrder)
                .Where(x => x.Method.Name == "TestThisMethod")
                .WhenArgumentsMatch(x => x.Get<WorkOrder>(1).workOrderId == 23)
                .MustHaveHappened();
        }
    }
}

Line 12 is a simple illustration of creating a fake object by passing arguments to the constructor of the class under test.

Line 14 to 17 is of interest to us.
Line 15 specifies the method we are interested in.
And line 16 is the place where it happens.  To Get we specify the type of the argument we are checking and then we specify the index at which this argument is there on the Function argument list. The indexing starts at zero.
Line 17 simply checks if the whole thing happened.

Now there are many ways to do unit testing. And this might not be the right way. But then all I wanted to show the options which are available in case you need it.

One thought on “FakeItEasy and verifying method parameters

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.