If you're a fun of writing tests in fluent style, you should definitely include FluentAssertions into your .Net test framework.
Install FluentAssertions
Installation is easy and fast, the simplest way is to use Package Manager Console in Visual Studio.
dotnet add <PROJECT_NAME> package -v <VERSION> FluentAssertions
So if you have project named my_project and want to add version 5.6.0, command will look like:
dotnet add my_project package -v 5.6.0 FluentAssertions
Proper version of package should be downloaded and added to your Dependencies\NuGet list for selected project.
Make your assertions fluent
Now, just include FluentAssertions in your .cs file
using FluentAssertions;
and replace standard nUnit Asserts with FluentAssertions
bool beFluent = false;
// standard nUnit assertion
Assert.IsTrue(beFluent);
// fluent
beFluent.Should().BeTrue();
When the code above is executed, output is
Expected beFluent to be true, but found False.
If you need include explanation, business justification or just more information for expected result to help you during failure analysis,
there is an optional string parameter 'because'
bool beFluent = false;
beFluent.Should().BeTrue("it is more readable");
will fail with message
Expected beFluent to be true because it is more readable, but found False.
FluentAssertions provide many more useful methods for many types
Comparing numbers
int theInt = 5;
theInt.Should().Be(5);
theInt.Should().BeGreaterOrEqualTo(5);
theInt.Should().BeOneOf(new List<int>() {1, 2, 3, 4, 5});
theInt.Should().BePositive();
theInt.Should().BeInRange(0, 20);
Comparing strings
string address = "https://qa-services.dev";
address.Should().Contain("qa");
address.Should().BeEmpty();
address.Should().MatchRegex("^\\w
quot;);
address.Should().NotBeNullOrEmpty();
address.Should().NotBe("http://qa-services.dev");
address.Should().StartWith("https");
Comparing Dates
Fluent Assertions provides extensions for handling dates in readable and convenient format
using FluentAssertions.Extensions;
which allows to use
DateTime birthday = 8.April(1985);
birthday.Should().NotBe(7.April(1985));
birthday.Should().HaveYear(1985);
birthday.Should().NotBeCloseTo(31.December(1985), TimeSpan.FromDays(30));
DateTime.Now.Should().BeAfter(birthday);
Comparing Collections
IEnumerable collection = new[] { 1, 2, 5, 8 };
collection.Should().NotBeEmpty()
.And.HaveCount(4)
.And.ContainInOrder(new[] { 2, 5 })
.And.ContainItemsAssignableTo<int>();
Explore more
Find full documentation on official website.
1 comment
Comments are closed.