Search code examples
c#xunitfluent-assertions

How to capture an exception thrown by an invocation using FluentAssertions


In FluentAssertions, how does one capture an exception thrown by an invocation? Exceptions shows basic code samples, but in my case I have a CustomException with a public enum. I'd like to assert that the correct enum value was thrown.

public class CustomException : Exception
{
   public MyEnum MyEnum { get; private set; }

   public CustomException(MyEnum myEnum)
   {
      MyEnum = myEnum;
   }
}

Solution

  • I believe you can use .Where() to apply a custom condition to the caught exception:

    act.Should().Throw<CustomException>().Where(e => e.MyEnum == MyEnum.Cheese);