View Javadoc
1   /*
2    * MIT License
3    * Copyright (c) 2006-2025 JMockit developers
4    * See LICENSE file for full license text.
5    */
6   package mockit.internal.expectations;
7   
8   import edu.umd.cs.findbugs.annotations.NonNull;
9   import edu.umd.cs.findbugs.annotations.Nullable;
10  
11  final class FailureState {
12      @NonNull
13      private final Thread testThread;
14      @Nullable
15      private Error errorThrownInAnotherThread;
16  
17      /**
18       * Holds an error associated to an ExpectedInvocation that is to be reported to the user.
19       * <p>
20       * This field is also set if and when an unexpected invocation is detected, so that any future invocations in this
21       * same phase execution can rethrow the original error instead of throwing a new one, which would hide the original.
22       * Such a situation can happen when test code or the code under test contains a "catch" or "finally" block where a
23       * mock invocation is made after a previous such invocation in the "try" block already failed.
24       */
25      @Nullable
26      private Error errorThrown;
27  
28      FailureState() {
29          testThread = Thread.currentThread();
30      }
31  
32      @Nullable
33      Error getErrorThrownInAnotherThreadIfAny() {
34          return errorThrownInAnotherThread;
35      }
36  
37      @Nullable
38      Error getErrorThrown() {
39          return errorThrown;
40      }
41  
42      void setErrorThrown(@Nullable Error error) {
43          errorThrown = error;
44      }
45  
46      void clearErrorThrown() {
47          errorThrown = null;
48      }
49  
50      void reportErrorThrownIfAny() {
51          if (errorThrown != null) {
52              if (testThread == Thread.currentThread()) {
53                  throw errorThrown;
54              }
55  
56              errorThrownInAnotherThread = errorThrown;
57          }
58      }
59  }