FluentAssertions is a set of .NET extension methods that allow you to more naturally specify the expected outcome of a TDD or BDD-style test. It is written by Dennis Doomen and Martin Opdam. For a quick overview, take a look at the documentation.
FluentAssertions allows us to convert something like this:
[Test]
public void ReturnsYellowForBananas()
{
var service = new FruitColorService();
var result = service.GetColorOf(new Banana());
Assert.AreEqual(Color.Yellow, result);
}
Into something like this:
[Test]
public void ReturnsYellowForBananas()
{
var service = new FruitColorService();
var result = service.GetColorOf(new Banana());
result.Should().Be(Color.Yellow);
}
It also allows for this kind of exception checking (here using the Microsoft.Visual.Studio. UnitTesting namespace instead of NUnit like in the previous examples):
[TestMethod()]
[ExpectedException(typeof(InvalidFruitException))]
public void ThrowsAnExceptionIfItIsNotAFruit()
{
var service = new FruitColorService();
var result = service.GetColorOf(new Tomato());
}
To become the following snippet. I preffer this way because it keeps the arrange, act, assert form:
[TestMethod()]
public void ThrowsAnExceptionIfItIsNotAFruit()
{
var service = new FruitColorService();
Action action = () => service.GetColorOf(new Tomato());
action.ShouldThrow<InvalidFruitException>();
}
I preffer the FluentAssertions way, but note that NUnit also has it’s fluent API for this purpose, using Assert.That in this case. the last two lines would become:
TestDelegate test = () => service.GetColorOf(new Tomato());
Assert.That(test, Throws.Exception
.TypeOf<InvalidFruitException>());
In contrast to the Microsoft TestTools.Assert, both FluentAssertions and NUnit try hard to make the error message as clear as possible, when a test fails you certainly want to know what is happening and not just that it broke plus a meaningless line number. This is true specially if you are not on the IDE where you can just click-and-go to the ofending test, but reading a report from your continuous integration server. For the second test in this post, FluentAssertions would print out something like:
Expected object to be Color [Yellow], but found Color [Green].
FluentAssertions has lots of usseful methods to work with DateTime, TimeSpan, Collections, String, etc. It became an essential tool in my everyday work, if you are into C#, give it a try!