Class AssertThrowsUtils

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

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

    Constructors
    Constructor Description
    AssertThrowsUtils()  
  • Method Summary

    Modifier and Type Method Description
    static Optional<Fix> tryFailToAssertThrows​(com.sun.source.tree.TryTree tryTree, List<? extends com.sun.source.tree.StatementTree> throwingStatements, Optional<com.sun.source.tree.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.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • AssertThrowsUtils

      public AssertThrowsUtils()
  • Method Details

    • tryFailToAssertThrows

      public static Optional<Fix> tryFailToAssertThrows​(com.sun.source.tree.TryTree tryTree, List<? extends com.sun.source.tree.StatementTree> throwingStatements, Optional<com.sun.source.tree.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).