Class AssertThrowsUtils
java.lang.Object
com.google.errorprone.bugpatterns.AssertThrowsUtils
Utility methods for refactoring try-fail pattern to assertThrows, which is preferred. Used by
TryFailRefactoring
and MissingFail
.-
Method Summary
Modifier and TypeMethodDescriptiontryFailToAssertThrows
(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'sassertThrows
, inserting the behavior of thetry
block into a lambda parameter, and assigning the expected exception to a variable, if it is used within thecatch
block.
-
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'sassertThrows
, inserting the behavior of thetry
block into a lambda parameter, and assigning the expected exception to a variable, if it is used within thecatch
block. For example:try { foo(); fail(); } catch (MyException expected) { assertThat(expected).isEqualTo(other); }
becomesMyException 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 thethrow
clause, excluding the fail statement.state
- current visitor state (for source positions).- Returns:
- an
Optional
containing aFix
that replacestryTree
with an equivalentassertThrows
, if possible. Returns anOptional.empty()
if a fix could not be constructed for the given code (e.g. multi-catch).
-