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(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 thetryblock into a lambda parameter, and assigning the expected exception to a variable, if it is used within thecatchblock.
-
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'sassertThrows, inserting the behavior of thetryblock into a lambda parameter, and assigning the expected exception to a variable, if it is used within thecatchblock. 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 thethrowclause, excluding the fail statement.state- current visitor state (for source positions).- Returns:
- an
Optionalcontaining aFixthat replacestryTreewith an equivalentassertThrows, if possible. Returns anOptional.empty()if a fix could not be constructed for the given code (e.g. multi-catch).
-