Search code examples
c#nunitfluent-assertions

FluentAssertions Throw() not listed to use


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.


Solution

  • 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>();    
    }