Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assertions using Fluent Assertions library

It seems that Fluent Assertions doesn't work within NUnit's Assert.Multiple block:

Assert.Multiple(() =>
    {
        1.Should().Be(2);
        3.Should().Be(4);
    });

When this code is run, the test fails immediately after the first assertion, so the second assertion is not even executed.

But, if I use NUnit's native assertions, I get the results I want:

Assert.Multiple(() =>
    {
        Assert.That(1, Is.EqualTo(2));
        Assert.That(3, Is.EqualTo(4));
    });

And the output contains details on both failures:

Test Failed - ExampleTest()

Message: Expected: 2 But was: 1

Test Failed - ExampleTest()

Message: Expected: 4 But was: 3

How can I get similar results using Fluent Assertions with NUnit?

like image 778
YMM Avatar asked Aug 30 '17 00:08

YMM


2 Answers

You can do this with assertion scopes like this:

using (new AssertionScope())
{
    5.Should().Be(10);
    "Actual".Should().Be("Expected");
}
like image 188
RonaldMcdonald Avatar answered Nov 09 '22 22:11

RonaldMcdonald


You may either:

1: Use AssertionScope (as pointed by @RonaldMcdonald):

using (new AssertionScope())
{
  (2 + 2).Should().Be(5);
  (2 + 2).Should().Be(6);
}

Or:

2. Use FluentAssertions.AssertMultiple NuGet package (the tiny package created by myself):

AssertMultiple.Multiple(() =>
{
    (2 + 2).Should().Be(5);
    (2 + 2).Should().Be(6);
});

And, when you import static member:

using static FluentAssertions.AssertMultiple.AssertMultiple;

//...

Multiple(() =>
{
    (2 + 2).Should().Be(5);
    (2 + 2).Should().Be(6);
});
like image 7
Dariusz Woźniak Avatar answered Nov 09 '22 22:11

Dariusz Woźniak