Class AssertThrowsUtils

java.lang.Object
com.google.errorprone.bugpatterns.AssertThrowsUtils

public final class AssertThrowsUtils extends Object
Utility methods for refactoring try-fail pattern to assertThrows, which is preferred. Used by TryFailRefactoring and MissingFail.
  • Method Details

    • tryFailToAssertThrows

      public static Optional<Fix> tryFailToAssertThrows(TryTree tryTree, List<? extends StatementTree> throwingStatements, Optional<Tree> failureMessage, VisitorState state)
      Transforms a try-catch block in the try-fail pattern into a call to JUnit's assertThrows, inserting the behavior of the try block into a lambda parameter, and assigning the expected exception to a variable, if it is used within the catch block. For example:
      try {
        foo();
        fail();
      } catch (MyException expected) {
        assertThat(expected).isEqualTo(other);
      }
      
      becomes
      MyException expected = assertThrows(MyException.class, () -> foo());
      assertThat(expected).isEqualTo(other);
      
      Parameters:
      tryTree - the tree representing the try-catch block to be refactored.
      throwingStatements - the list of statements in the throw clause, excluding the fail statement.
      state - current visitor state (for source positions).
      Returns:
      an Optional containing a Fix that replaces tryTree with an equivalent assertThrows, if possible. Returns an Optional.empty() if a fix could not be constructed for the given code (e.g. multi-catch).