@@ -32,6 +32,7 @@ public class TestEnvironmentImpl {
3232 public static void AddBeforeAfterTest ( Func < IDisposable > beforeAfterTest ) => Instance ? . AddBeforeAfterTestAction ( beforeAfterTest ) ;
3333
3434 private readonly AsyncLocal < List < Func < IDisposable > > > _beforeAfterTestActions = new AsyncLocal < List < Func < IDisposable > > > ( ) ;
35+ private readonly AsyncLocal < Stack < IDisposable > > _beforeAfterTestActionDisposables = new AsyncLocal < Stack < IDisposable > > ( ) ;
3536 private readonly AsyncLocal < TaskObserver > _taskObserver = new AsyncLocal < TaskObserver > ( ) ;
3637 private readonly AsyncLocal < Stopwatch > _stopwatch = new AsyncLocal < Stopwatch > ( ) ;
3738 private readonly AssemblyLoader _assemblyLoader = new AssemblyLoader ( ) ;
@@ -67,19 +68,32 @@ protected virtual void BeforeTestRun(string testFullName, int secondsTimeout) {
6768 _stopwatch . Value . Start ( ) ;
6869 TestData . SetTestRunScope ( testFullName ) ;
6970
70- var disposables = new Stack < IDisposable > ( ) ;
71- try {
72- foreach ( var beforeAfterTestAction in beforeAfterTestActions ) {
73- disposables . Push ( beforeAfterTestAction ( ) ) ;
71+ if ( beforeAfterTestActions != null ) {
72+ var disposables = new Stack < IDisposable > ( ) ;
73+ try {
74+ foreach ( var beforeAfterTestAction in beforeAfterTestActions ) {
75+ disposables . Push ( beforeAfterTestAction ( ) ) ;
76+ }
77+ } catch ( Exception ) {
78+ RunDisposablesSafe ( disposables ) ;
79+ throw ;
7480 }
75- } catch ( Exception ) {
76- RunDisposables ( disposables ) ;
77- throw ;
81+
82+ _beforeAfterTestActionDisposables . Value = disposables ;
7883 }
7984 }
8085
8186 protected virtual void AfterTestRun ( ) {
8287 try {
88+ var disposables = _beforeAfterTestActionDisposables . Value ;
89+ _beforeAfterTestActionDisposables . Value = null ;
90+ if ( disposables != null ) {
91+ var afterTestRunException = RunDisposablesSafe ( disposables ) ;
92+ if ( afterTestRunException != null ) {
93+ throw afterTestRunException ;
94+ }
95+ }
96+
8397 _taskObserver . Value ? . WaitForObservedTask ( ) ;
8498 _stopwatch . Value ? . Stop ( ) ;
8599 TestData . ClearTestRunScope ( ) ;
@@ -94,14 +108,18 @@ private void AddBeforeAfterTestAction(Func<IDisposable> beforeAfterTest) {
94108 actions . Add ( beforeAfterTest ) ;
95109 }
96110
97- private void RunDisposables ( Stack < IDisposable > disposables ) {
111+ private AggregateException RunDisposablesSafe ( Stack < IDisposable > disposables ) {
112+ var exceptions = new List < Exception > ( ) ;
98113 while ( disposables . Count > 0 ) {
99114 var disposable = disposables . Pop ( ) ;
100115 try {
101116 disposable . Dispose ( ) ;
102- } catch ( Exception ) {
117+ } catch ( Exception ex ) {
118+ exceptions . Add ( ex ) ;
103119 }
104120 }
121+
122+ return exceptions . Count > 0 ? new AggregateException ( exceptions ) : null ;
105123 }
106124 }
107125}
0 commit comments