Let's Write Tests
Explore writing foundational unit tests in JUnit by creating test cases that cover various code paths in Java methods. Understand how to organize test data and assert expected outcomes while maintaining clarity and reducing redundancy across tests.
We'll cover the following...
The bulk of the “interesting” logic in matches() resides in the body of the for loop in the Profile class.
First test: Covering one path
Let’s write a simple test that covers one path through the loop.
Two points that are evident from the code:
- We need a
Profileinstance. - We need a
Criteriaobject to pass as an argument tomatches().
By analyzing the code in matches() and looking at the constructors of Criteria, Criterion, and Question, we can figure out how to piece together a useful Criteria object.
The analysis lets us write this part of the arranged portion of the test. Press the Run button below to execute the test code.: ...