How to use Fluent Assertions Should().Throw() with NOT hardcoded exception type?

199 views Asked by At

I would like to use fluent assertions .Should().Throw, but do not want to hardcode the type of the expected exception, instead I want it parametrized, so it is in a variable which type is Type.

Without parametrized it should be the following:

Action act = () => sut.MyMethod();
act.Should().Throw<MyException>().Where(myPredicate);

However I would like to the type of MyException to be a parameter in a variable

1

There are 1 answers

1
lg2de On

FluentAssertion's API is generation. So, currently you must provide at least the base class of all exception: Exception. Then, you can validate the type using BeOfType.

act.Should().Throw<Exception>().Which.Should().BeOfType(typeof(MyException));