rspec/rules/S5977/java/rule.adoc

73 lines
2.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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 https://github.com/jlink/jqwik[jqwik].
This rule raises an issue when ``++new Random()++`` or ``++UUID.randomUUID()++`` are called in test code.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
int userAge = new Random().nextInt(42); // Noncompliant
UUID userID = UUID.randomUUID(); // Noncompliant
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
int userAge = 31;
UUID userID = UUID.fromString("00000000-000-0000-0000-000000000001");
----
== Resources
2021-04-28 16:49:39 +02:00
* https://phauer.com/2019/modern-best-practices-testing-java/#use-fixed-data-instead-of-randomized-data[Modern Best Practices for Testing in Java - Philipp Hauer]
* https://jqwik.net/[Jqwik test engine]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace randomly generated values with fixed ones.
=== Highlighting
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.
'''
== Comments And Links
(visible only on this page)
=== on 4 Sep 2020, 11:46:33 Nicolas Harraudeau wrote:
Note that https://phauer.com/2019/modern-best-practices-testing-java/#use-parameterized-tests[Modern Best Practices for Testing in Java - Philipp Hauer] also mentions ``++Instant.now()++`` as a source or randomness, however there can be valid use cases for using the current time, such as timing some operation. Forbidding ``++Instant.now()++`` would raise False Positives.
endif::env-github,rspecator-view[]