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 byTryFailRefactoring
andMissingFail
.
-
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description 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'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 Detail
-
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'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).
-
-