You assert that something happened, but why?
TL;DR: Be explicit when creating tests to ensure clarity and maintainability
Problems
Readability
Coupling to external databases, global state or singletons, static methods or external services
Maintenance Difficulty
Debugging Complexity
Hidden Dependencies
Solutions
Be Explicit
Inline the setup
Use dependency Injection
Use mocking with caution
Context
Your test depends on external data or configurations not immediately visible within the test itself.
This obscures the test’s setup, making it difficult for someone reading it to understand what is being tested and why it might fail.
Every test case should have three stages:
Setup: Initialize and configure everything needed for the test.
Exercise: Execute the code being tested.
Assert: Verify the expected outcome.
All of them must be explicit
Sample Code
Wrong
@Test
void shouldReturnAnswerWhenAnswerExists() {
User answer = KnowledgeRepository.findAnswerToQuestion(42);
assertNotNull(answer);
}
Right
@Test
void shouldReturnAnswerWhenAnswerExists() {
KnowledgeRepository knowledgeRepository =
new InMemoryKnowledgeRepository();
Answer expectedAnswer = new Answer(42, "The Ultimate");
knowledgeRepository.save(expectedAnswer);
Answer actualAnswer = answerRepository.findAnswerToQuestion(42);
assertNotNull(actualAnswer);
assertEquals(expectedAnswer, actualAnswer);
}
Detection
[X] Manual
You can detect this smell by looking for tests that do not clearly show their setup steps or rely heavily on external configurations.
Tags
- Test Smells
Level
[x] Intermediate
AI Generation
AI-generated code often avoids this smell due to the tendency to create small, isolated examples.
AI Detection
Most AI Detectors fail to identify this as a problem unless you point it out explicitly.
Conclusion
This code smell is especially prevalent in legacy codebases or when consistent testing practices are lacking.
You need to be explicit of the environment since tests must always be in "full environmental control"
Relations
Code Smell 18 — Static Functions
Maxi Contieri ・ Nov 6 '20
More Info
Coupling: The one and only software design problem
Maxi Contieri ・ Feb 6 '21
Disclaimer
Code Smells are my opinion.
Credits
Photo by Brands&People on Unsplash
Science is what we understand well enough to explain to a computer, Art is all the rest
Donald Knuth
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (0)