8

I'm using FluentAssertions with NUnit and I realize that the method Throw() and other related methods is not listed for me to use. Do I have to install any other package to have access to this method?

I'm using the last release, 5.4.2, installed by NuGet.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179

1 Answers1

19

The documentation doesn't make it very clear, but Should().Throw() has to be applied to an Action (or, as pointed out by @ArturKrajewski in a comment below, a Func and also async calls):

Action test = () => throw new InvalidOperationException();
test.Should().Throw<InvalidOperationException>();

So the tests could look like this:

public class AssertThrows_ExampleTests {
    [Test]
    public void Should_Throw_Action() {
        var classToTest = new TestClass();

        // Action for sync call
        Action action = () => classToTest.MethodToTest();
        action.Should().Throw<InvalidOperationException>();
    }

    [Test]
    public void Should_Throw_Action_Async() {
        var classToTest = new TestClass();

        // Func<Task> required here for async call
        Func<Task> func = async () => await classToTest.MethodToTestAsync();
        func.Should().Throw<InvalidOperationException>();
    }

    private class TestClass {
        public void MethodToTest() {
            throw new InvalidOperationException();
        }

        public async Task MethodToTestAsync() {
            throw new InvalidOperationException();
        }
    }
}

Or - in Fluent Assertions 5 or later - like this:

[Test]
public async Task Should_Throw_Async() {
    var classToTest = new TestClass();

    var test = async () => await classToTest.MethodToTestAsync();
    await test.Should().ThrowAsync<InvalidOperationException>();    
}
stuartd
  • 70,509
  • 14
  • 132
  • 163
  • 2
    Since 5.5.0 also`Func` supports `Should().Throw()` and similar assertions. Additionally, async scenarios for `Func` and `Func>` are supported as well. – Artur Krajewski Nov 19 '18 at 20:27