Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test Smell: it is not a good practice to use the loop in the test #3928

Open
TestSmell opened this issue Aug 17, 2022 · 1 comment
Open

Test Smell: it is not a good practice to use the loop in the test #3928

TestSmell opened this issue Aug 17, 2022 · 1 comment
Labels

Comments

@TestSmell
Copy link

Hi!

We notice that you use the loop structure in your test cases.
For example, testInvalidChar() in NoiseCharactersTest.java
image

However, using the loop in test cases is not a good test practice.

We analyzed the relevant Stack Overflow posts and summarized four potential negatives it brings:

  1. Loops make the test case more complex.
  2. In most cases, a loop can be replaced with a data-driven test that is more readable.
  3. Loops break the assert-for-one-thing thumb rule. I don't mean a single assert statement.
  4. When a test fails, knowing the reason is more complicated.

Solution:
To avoid using the loop in the test, JUnit provides an annotation (i.e., @ParameteredTest), which can enable a test case to run multiple times with different parameters.
Therefore, the code can be refactored as:

@test
@ParameteredTest
@@valuesource(invalidPatterns = {"", "1", "ABC", "\u21", "#x0001-#x0000"
, "#x0001 - #x - #x0000", "#x0000 #x0022"})
public void testInvalidChar(String i) {
assertThrows(IllegalArgumentException.class, () -> {
myFilter.add(i);
});
}

@jamesagnew
Copy link
Collaborator

This could probably be replaced with a parameterized test, and a PR implementing that would be accepted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants