Core Java · 325 words · 2 minute read
Testing Small Java Methods: Contracts, Boundaries, and Evidence
By Priyanshu Rauth · Published 2026-09-04 · Updated 2026-09-04
Testing starts before a framework. A method is easy to test when its inputs, output, side effects, and invalid-input behavior are stated plainly. “Find the maximum” is incomplete until you decide whether empty arrays are rejected, return an optional result, or have some default. Small pure methods make these decisions visible because they return a value instead of printing from the middle of their logic.
Turn a rule into examples
Choose one ordinary case, one boundary case, and one case that breaks a tempting incorrect solution. For a maximum, test a mixed array, an all-negative array, and an empty array under the chosen contract. For a palindrome, test a one-character String, mismatched case if case is ignored, and punctuation if punctuation is ignored. A test is evidence for a specific rule, not a decorative extra input.
public class Main {
static boolean isEven(int value) {
return value % 2 == 0;
}
public static void main(String[] args) {
System.out.println(isEven(14));
System.out.println(isEven(-3));
}
}The output is true. Negative values are useful here because the definition depends on a zero remainder, not on a number being positive.
false
Separate calculation from presentation
Let a method return an int, boolean, object, or collection; let main format it for a person. This keeps the calculation reusable and allows the same method to be exercised with several inputs without parsing console text. For code that changes an array or object, assert both the returned result and the visible postcondition.
Common mistakes
- Writing only a happy-path test.
- Testing implementation details instead of the method’s observable contract.
- Using a single test case to justify a complexity claim.
- Printing from every helper method and making output order part of hidden logic.
Practice next
Use the test cases on factorial, binary search, and coin change as a starting point. Change one value in the online compiler, predict the result, then run it. That prediction step is often where missing contracts become obvious.
Continue with the Java practice path · Try code in the Java compiler