1+ using System ;
2+ using NUnit . Framework ;
3+ using NUnit . Framework . Interfaces ;
4+ using NUnit . Framework . Internal ;
5+ using NUnit . Framework . Internal . Commands ;
6+
7+ namespace FluentAssertions . Analyzers . FluentAssertionAnalyzerDocs ;
8+
9+ /// <summary>
10+ /// Based on https://github.com/nunit/nunit-csharp-samples/blob/master/ExpectedExceptionExample/ExpectedExceptionAttribute.cs
11+ /// </summary>
12+ [ AttributeUsage ( AttributeTargets . Method , AllowMultiple = false , Inherited = false ) ]
13+ public class ExpectedAssertionExceptionAttribute : NUnitAttribute , IWrapTestMethod
14+ {
15+ public TestCommand Wrap ( TestCommand command )
16+ {
17+ return new ExpectedExceptionCommand ( command , typeof ( AssertionException ) ) ;
18+ }
19+
20+ private class ExpectedExceptionCommand : DelegatingTestCommand
21+ {
22+ private readonly Type _expectedType ;
23+
24+ public ExpectedExceptionCommand ( TestCommand innerCommand , Type expectedType )
25+ : base ( innerCommand )
26+ {
27+ _expectedType = expectedType ;
28+ }
29+
30+ public override TestResult Execute ( TestExecutionContext context )
31+ {
32+ Type caughtType = null ;
33+
34+ try
35+ {
36+ innerCommand . Execute ( context ) ;
37+ }
38+ catch ( Exception ex )
39+ {
40+ if ( ex is NUnitException )
41+ ex = ex . InnerException ;
42+ caughtType = ex . GetType ( ) ;
43+ }
44+
45+ if ( caughtType == _expectedType )
46+ context . CurrentResult . SetResult ( ResultState . Success ) ;
47+ else if ( caughtType != null )
48+ context . CurrentResult . SetResult ( ResultState . Failure ,
49+ $ "Expected { _expectedType . Name } but got { caughtType . Name } ") ;
50+ else
51+ context . CurrentResult . SetResult ( ResultState . Failure ,
52+ $ "Expected { _expectedType . Name } but no exception was thrown") ;
53+
54+ return context . CurrentResult ;
55+ }
56+ }
57+ }
0 commit comments