Testing Utility Classes
What you'll learn: You'll learn how to write unit tests for static utility methods and why stateless design makes testing easier.
Why Static Methods Are Easy to Test
Utility classes with pure static methods (functions that don't modify or depend on mutable state) are some of the easiest code to test. Since they don't rely on instance variables or hidden state, you simply call the method with inputs and verify the output—no object setup required.
Think of it like testing a calculator: press "2 + 2" and expect "4" every single time, regardless of what calculation you did before.
Writing Tests for Utility Methods
When testing static methods:
// Example utility class (from previous lesson)
public class MathUtils {
private MathUtils() {} // prevent instantiation
public static int add(int a, int b) {
return a + b;
}
public static boolean isEven(int n) {
return n % 2 == 0;
}
}
// Test class
public class MathUtilsTest {
public void testAdd() {
int result = MathUtils.add(2, 3);
if (result != 5) {
throw new AssertionError("Expected 5, got " + result);
}
}
public void testIsEven() {
if (!MathUtils.isEven(4)) {
throw new AssertionError("4 should be even");
}
if (MathUtils.isEven(3)) {
throw new AssertionError("3 should not be even");
}
}
}
Why Statelessness Matters
Stateless utility functions (pure functions) make testing predictable because:
- Same inputs always produce same outputs
- No need to set up object state before each test
- Tests can run in any order without interference
- No hidden dependencies to mock or stub
If your utility methods accessed or modified static fields, tests could affect each other, making them fragile and order-dependent.
Key Takeaway: Static utility methods that are stateless (pure functions) are highly testable—just call them with inputs and verify outputs, with no setup or state management required.