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

Tests should use fixed data instead of randomized data

    XMLWordPrintable

    Details

    • Message:
      Replace randomly generated values with fixed ones.
    • Highlighting:
      Hide

      Primary locations:

      • The first call to new Random() in a file.
      • The first call to UUID.randomUUID() in a file.

      Secondary locations:

      • The following calls to new Random() or UUID.randomUUID() in the file.
      Show
      Primary locations: The first call to new Random() in a file. The first call to UUID.randomUUID() in a file. Secondary locations: The following calls to new Random() or UUID.randomUUID() in the file.
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Level:
      Syntactic Analysis
    • Analysis Scope:
      Test Sources

      Description

      Tests should always:

      • Make sure that production code behaves as expected, including edge cases.
      • Be easy to debug, i.e. understandable and reproducible.

      Using random values in tests will not necessarily check edge cases, and it will make test logs a lot harder to read. It is better to use easily readable hardcoded values. If this makes your code bigger you can use helper functions.

      There is one valid use case for random data in tests: when testing every value would make tests impractically slow. In this case the best you can do is use random to test every value on the long run. You should however make sure that random values are logged so that you can reproduce failures. Some libraries exist to make all this easier. You can for example use property-based testing libraries such as jqwik.

      This rule raises an issue when new Random() or UUID.randomUUID() are called in test code.

      Noncompliant Code Example

      int userAge = new Random().nextInt(42);  // Noncompliant
      UUID userID = UUID.randomUUID(); // Noncompliant
      

      Compliant Solution

      int userAge = 31;
      UUID userID = UUID.fromString("00000000-000-0000-0000-000000000001");
      

      See

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              margarita.nedzelska Margarita Nedzelska
              Reporter:
              nicolas.harraudeau Nicolas Harraudeau (Inactive)
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: