Sunday, 24 January 2016

Unit Test (#1) : Getting started with xUnit & Fluent Assertion

Unit testing is the process in which the programmer will test the accuracy and adequacy of functions he has written. They must produce expected output against given input.

This tutorial will show you how to create and run a simple test with xUnit and Fluent Assertion.

Getting started with a simple test

Let's start by creating a Console Application, targeting .NET 4.5 (or later). Open Visual Studio, and choose File > New > Project:

Next, before we can do the test, we must install necessary packages: xUnit.net, xUnit.net Runner, Fluent Assertions. Right click to the test project > choose Manage NuGet Packages…

In the search box in the upper right corner, type "xunit". Select and install xUnit.net, xUnit.net [Runner: Visual Studio]

Do the same for Fluent Assertions

Create your first test

OK, now let’s create a new class called Test.cs in Solution Explorer and begin to write some simple tests. See the code below:
using Xunit;
using FluentAssertions;
namespace MyFirstTest
{
    public class Test
    {
        int Add(int x, int y)
        {
            return x + y;
        }

        [Fact]
        void FactTest()
        {
            Add(2, 2).Should().Be(4);
        }

        [Theory]
        [InlineData(2,3,5)]
        [InlineData(3,3,7)]
        void TheoryTest(int a, int b, int sum)
        {
            sum.Should().Be(Add(a, b));
        }
    }
}
To run it, On the Menu > click Test > Run > All Tests

The test runner starts running and after it finished, the result would be like this:

As you can see, in the code above, before very test function, there is an option which enclosed by the brackets.
[Fact]
void FactTest(){…}

[Theory]
[InlineData(2,3,5)]
[InlineData(3,3,7)]
void TheoryTest(int a, int b, int sum){…}
Those are types of unit test. xUnit.net supports two different major types: facts and theories:

Facts are tests which are always true. They test invariant conditions.

Theories are tests which are only true for a particular set of data.

At the first test, we want to test if Add(2, 2) function returns 4 or not.

In Fluent Assertions way, we can write :
Add(2,2).Should().Be(4);

It says that if Add(2,2) really returns 4, the test will be passed. If not, the test will be failed.

You can also write it in Assert way :
Assert.Equal(Add(2,2),4);

But obviously the first statement is more naturally than the second one. Moreover, Fluent Assertions not only use clearly named assertion methods, but also make sure the failure message provides as much information as possible. That was the reason why we used Fluent Assertions syntax here rather than original grammar.

No comments :

Post a Comment