FluentAssertions Throw() not listed to use
Asked Answered
I

1

9

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.

Ilyssa answered 7/11, 2018 at 21:57 Comment(2)
Do you mean Should().Throw() or Assert.Throws()?Humorous
Should().Throw()Ilyssa
H
20

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>();    
}
Humorous answered 8/11, 2018 at 0:20 Comment(1)
Since 5.5.0 alsoFunc<T> supports Should().Throw() and similar assertions. Additionally, async scenarios for Func<Task> and Func<Task<T>> are supported as well.Transport

© 2022 - 2024 — McMap. All rights reserved.