Details
-
Type:
Code Smell Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:
-
Message:Remove this failure assertion and simply add the exception type to the method signature.
-
Highlighting:
- Primary: Assert.fail
- Secondary: try and catch (...)
-
Default Severity:Minor
-
Impact:Low
-
Likelihood:Low
-
Covered Languages:Java
-
Remediation Function:Constant/Issue
-
Constant Cost:2min
-
Analysis Scope:Test Sources
Description
When the code under test in a unit test throws an exception, the test itself fails. Therefore, there is no need to surround the tested code with a try-catch structure to detect failure. Instead, you can simply move the exception type to the method signature.
This rule raises an issue when there is a fail assertion inside a catch block.
Noncompliant Code Example
@Test public void testMethod() { try { // Some code } catch (MyException e) { Assert.fail(e.getMessage()); // Noncompliant } }
Compliant Solution
@Test public void testMethod() throws MyException { // Some code }
Attachments
Issue Links
- is implemented by
-
SONARJAVA-1750 Rule S3658: Unit test should throw exception instead of failing in a catch block
-
- Closed
-
- is related to
-
SONARJAVA-3397 S3658, S5778, S5779, S5783 support AssertJ "fail"
-
- Closed
-
-
RSPEC-3431 "[ExpectedException]" should not be used
- Active
1.
|
Java | RSPEC-5775 |
|
Active | Unassigned |