Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-3658

Unit tests should throw exceptions

    XMLWordPrintable

    Details

    • 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

          1.
          Java RSPEC-5775 Language-Specification Active Unassigned

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              nicolas.peru Nicolas Peru
              Votes:
              1 Vote for this issue
              Watchers:
              2 Start watching this issue

                Dates

                Created:
                Updated: