There are so many unit test frameworks available for .Net such as NUnit, xUnit and MSTest. They all have their own ways to assert the object or sut.
If you are working on multiple projects or you change the project to work on another and if they have different unit test frameworks than you are familiar with, it becomes a problem.
Fluent Assertions supports most of the popular unit test frameworks and you can assert using its extension methods on the sut or objects. That solves problem of keeping up with other frameworks for assertion. You just need to remember how Fluent Assertion works (and trust me it is easy to remember and use) regardless of the unit test framework you use.
We will see how to setup it for your .Net project followed by some examples.
1) Right click on the Test Project and select Manage NuGet Package
2) Search for FluentAssertions in browse section.
3) Click on it and select install option.
4) Click on OK when you see popup like below:
So that was about how to setup.
Now time for the action.
Program.cs looks like below:
namespace Calculator
{
public static class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two numbers for addition please: ");
int.TryParse(Console.ReadLine(), out int num1);
int.TryParse(Console.ReadLine(), out int num2);
var sum = Calculator.Addition(num1, num2);
Console.WriteLine($"Result of the addition is: {sum}");
}
}
public static class Calculator
{
public static int Addition(int number1, int number2)
{
return number1 + number2;
}
public static int Subtraction(int number1, int number2)
{
return number1 - number2;
}
public static int Multiplication(int number1, int number2)
{
return number1 * number2;
}
public static int Division(int number1, int number2)
{
return number1 / number2;
}
}
}
Here are some examples of the Unit Tests.
using FluentAssertions;
using NUnit.Framework;
namespace Calculator.Tests
{
public class Tests
{
[SetUp]
public void Setup()
{
}
[Test]
public void Addition_Should_Return_Result()
{
int number1 = 5;
int number2 = 10;
var result = Calculator.Addition(number1, number2);
result.Should().Be(15);
}
[Test]
public void Division_Should_Return_Result()
{
int number1 = 10;
int number2 = 5;
var result = Calculator.Division(number1, number2);
result.Should().Be(2);
}
[Test]
public void Division_Should_Throw_Exception_When_Divided_By_Zero()
{
int number1 = 10;
int number2 = 0;
Action act = () => Calculator.Division(number1, number2);
act.Should().Throw<DivideByZeroException>();
}
}
}
So the Should() method is an extension method that does the magic. You must use Should() on the sut or object you wish to assert. It further have various extension methods such as .Be(), .BeGreaterThan(), BePositive(), NotBe().
To learn more, visit official website: https://fluentassertions.com/introduction
Top comments (0)