Friday, September 11, 2015

Make your Unit test easy using Fluent Assertions



Fluent Assertions is a set of .NET extension methods that allow you to more naturally specify the expected outcome of a TDD. Sometime, we need to check various parameters to ensure that return result is correct from function. Fluent Assertions gives set of extension method to verify test result.
For example, there might be some function which will generate employee Id for new join employee and the condition to create employee Id might be something like this.


  • It should start by “E” character.
  • Should contain “EMP”
  • Should ends with “CMP” (may be CMP stands for Company name J)
  • The length should 9.

So, to check all those parameters we need to write bunch of if-else if we don’t use some smart mechanism. Using Fluent Assertion , we can check all those conditions using a single line of code.
Here is our test class which will return one static employee Id.

  class TestClass
    {
        public string ReturnEmployeeID()
        {
            return "EMP123CMP";
        }
    }

And in unit test method, we are checking whether the returned value is correct or not.

[TestClass]
    public class UnitTestClass
    {
        [TestMethod]
        public void Add_Test_Function()
        {
           new Code.TestClass().ReturnEmployeeID().
Should().StartWith("E").And.EndWith("CMP").
And.Contain("EMP").And.HaveLength(9);
        }
    }

And once we run the case, we will see that the case is getting pass.



It supports the following .NET versions.
  • .NET 4.0 and 4.5
  • Windows Store Apps for Windows 8 and 8.1
  • Silverlight 5
  • Windows Phone 8.1
  • Windows Phone Silverlight 8.0 and 8.1
  • Portable Class Libraries
It supports the following unit test frameworks:

 



2 comments:

  1. Bro its nice article ,but I couldn't undersatand constructor code.where is fluent assertion method .plz clarify once

    ReplyDelete
  2. This is fluent assertion method.

    new Code.TestClass().ReturnEmployeeID().
    Should().StartWith("E").And.EndWith("CMP").
    And.Contain("EMP").And.HaveLength(9);

    ReplyDelete