Unit Testing Boundary Conditions and Edge Cases
Overview
Systematic patterns for testing boundary conditions, corner cases, and limit values in Java using JUnit 5. Covers numeric boundaries, string edge cases, collection states, floating-point precision, date/time limits, and off-by-one scenarios.
When to Use
- Numeric min/max limits, null/empty/whitespace inputs
- Overflow/underflow validation, collection boundaries
- Off-by-one errors, floating-point precision
Instructions
- Identify boundaries: List numeric limits (MIN_VALUE, MAX_VALUE, zero), string states (null, empty, whitespace), collection sizes (0, 1, many)
- Apply parameterized tests: Use
@ParameterizedTest with @ValueSource or @CsvSource for multiple boundary values
- Test both sides of boundaries: Cover values just below, at, and just above each boundary
- Run tests after adding each boundary category to catch issues early
- Verify floating-point precision: Use
isCloseTo(expected, within(tolerance)) with AssertJ
- Test collection states: Explicitly test empty (0), single (1), and many (>1) element scenarios
- Handle overflow/underflow: Use
Math.addExact() and Math.subtractExact() to detect arithmetic overflow
- Test date/time edges: Verify leap years, month boundaries, timezone transitions
- Iterate based on failures: When a boundary test fails, analyze the error to discover additional untested boundaries; add test cases for the newly discovered edge conditions
Examples
Requires: junit-jupiter, junit-jupiter-params, assertj-core.
Integer Boundary Testing
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.assertj.core.api.Assertions.*;
class IntegerBoundaryTest {
@ParameterizedTest
@ValueSource(ints = {Integer.MIN_VALUE, Integer.MIN_VALUE + 1, 0, Integer.MAX_VALUE - 1, Integer.MAX_VALUE})
void shouldHandleIntegerBoundaries(int value) {
assertThat(value).isNotNull();
}
@Test
void shouldDetectIntegerOverflow() {
assertThatThrownBy(() -> Math.addExact(Integer.MAX_VALUE, 1))
.isInstanceOf(ArithmeticException.class);
}
@Test
void shouldDetectIntegerUnderflow() {
assertThatThrownBy(() -> Math.subtractExact(Integer.MIN_VALUE, 1))
.isInstanceOf(ArithmeticException.class);
}
@Test
void shouldHandleZeroEdge() {
int result = MathUtils.divide(0, 5);
assertThat(result).isZero();
assertThatThrownBy(() -> MathUtils.divide(5, 0))
.isInstanceOf(ArithmeticException.class);
}
}
String Boundary Testing
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
class StringBoundaryTest {
@ParameterizedTest
@ValueSource(strings = {"", " ", " ", "\t", "\n"})
void shouldRejectEmptyAndWhitespace(String input) {
boolean result = StringUtils.isNotBlank(input);
assertThat(result).isFalse();
}
@Test
void shouldHandleNullString() {
String result = StringUtils.trim(null);
assertThat(result).isNull();
}
@Test
void shouldHandleSingleCharacter() {
assertThat(StringUtils.capitalize("a")).isEqualTo("A");
assertThat(StringUtils.trim("x")).isEqualTo("x");
}
@Test
void shouldHandleVeryLongString() {
String longString = "x".repeat(1000000);
assertThat(longString.length()).isEqualTo(1000000);
assertThat(StringUtils.isNotBlank(longString)).isTrue();
}
}
Collection Boundary Testing
class CollectionBoundaryTest {
@Test
void shouldHandleEmptyList() {
List<String> empty = List.of();
assertThat(empty).isEmpty();
assertThat(CollectionUtils.first(empty)).isNull();
assertThat(CollectionUtils.count(empty)).isZero();
}
@Test
void shouldHandleSingleElementList() {
List<String> single = List.of("only");
assertThat(single).hasSize(1);
assertThat(CollectionUtils.first(single)).isEqualTo("only");
assertThat(CollectionUtils.last(single)).isEqualTo("only");
}
@Test
void shouldHandleLargeList() {
List<Integer> large = new ArrayList<>();
for (int i = 0; i < 100000; i++) {
large.add(i);
}
assertThat(large).hasSize(100000);
assertThat(CollectionUtils.first(large)).isZero();
assertThat(CollectionUtils.last(large)).isEqualTo(99999);
}
@Test
void shouldHandleNullInCollection() {
List<String> withNull = new ArrayList<>(List.of("a", null, "c"));
assertThat(withNull).contains(null);
assertThat(CollectionUtils.filterNonNull(withNull)).hasSize(2);
}
}
Floating-Point Boundary Testing
class FloatingPointBoundaryTest {
@Test
void shouldHandleFloatingPointPrecision() {
double result = 0.1 + 0.2;
assertThat(result).isCloseTo(0.3, within(0.0001));
}
@Test
void shouldHandleSpecialFloatingPointValues() {
assertThat(Double.POSITIVE_INFINITY).isGreaterThan(Double.MAX_VALUE);
assertThat(Double.NEGATIVE_INFINITY).isLessThan(Double.MIN_VALUE);
assertThat(Double.NaN).isNotEqualTo(Double.NaN);
}
@Test
void shouldHandleZeroInDivision() {
assertThat(1.0 / 0.0).isEqualTo(Double.POSITIVE_INFINITY);
assertThat(-1.0 / 0.0).isEqualTo(Double.NEGATIVE_INFINITY);
assertThat(0.0 / 0.0).isNaN();
}
}
Date/Time Boundary Testing
class DateTimeBoundaryTest {
@Test
void shouldHandleMinAndMaxDates() {
LocalDate min = LocalDate.MIN;
LocalDate max = LocalDate.MAX;
assertThat(min).isBefore(max);
assertThat(DateUtils.isValid(min)).isTrue();
assertThat(DateUtils.isValid(max)).isTrue();
}
@Test
void shouldHandleLeapYearBoundary() {
LocalDate leapYearEnd = LocalDate.of(2024, 2, 29);
assertThat(leapYearEnd).isNotNull();
}
@Test
void shouldRejectInvalidDateInNonLeapYear() {
assertThatThrownBy(() -> LocalDate.of(2023, 2, 29))
.isInstanceOf(DateTimeException.class);
}
}
Array Index Boundary Testing
class ArrayBoundaryTest {
@Test
void shouldHandleFirstElementAccess() {
int[] array = {1, 2, 3, 4, 5};
assertThat(array[0]).isEqualTo(1);
}
@Test
void shouldHandleLastElementAccess() {
int[] array = {1, 2, 3, 4, 5};
assertThat(array[array.length - 1]).isEqualTo(5);
}
@Test
void shouldThrowOnNegativeIndex() {
int[] array = {1, 2, 3};
assertThatThrownBy(() -> array[-1])
.isInstanceOf(ArrayIndexOutOfBoundsException.class);
}
@Test
void shouldThrowOnOutOfBoundsIndex() {
int[] array = {1, 2, 3};
assertThatThrownBy(() -> array[10])
.isInstanceOf(ArrayIndexOutOfBoundsException.class);
}
@Test
void shouldHandleEmptyArray() {
int[] empty = {};
assertThat(empty.length).isZero();
assertThatThrownBy(() -> empty[0])
.isInstanceOf(ArrayIndexOutOfBoundsException.class);
}
}
Best Practices
- Test at boundaries explicitly: don't rely on random testing
- Test null and empty separately from valid inputs
- Use parameterized tests for multiple boundary cases
- Test both sides of boundaries (just below, at, just above)
- Verify error messages for invalid boundary inputs
- Document why specific boundaries matter for your domain
- Test overflow/underflow for all numeric operations
Constraints and Warnings
- Integer overflow: Use
Math.addExact() to detect silent overflow
- Floating-point precision: Never use exact equality; always use tolerance-based assertions
- NaN behavior:
NaN != NaN; use Float.isNaN() or Double.isNaN()
- Collection size limits: Be mindful of memory with large test collections
- String encoding: Test with Unicode characters for internationalization
- Date/time boundaries: Account for timezone transitions and daylight saving
- Array indexing: Always test index 0, length-1, and out-of-bounds
References
1---
2name: unit-test-boundary-conditions
3description: Provides edge case, corner case, boundary condition, and limit testing patterns for Java unit tests. Validates minimum/maximum values, null cases, empty collections, numeric overflow/underflow, floating-point precision, and off-by-one scenarios using JUnit 5 and AssertJ. Use when writing .java test files to ensure code handles limits, corner cases, and special inputs correctly.
4allowed-tools: Read, Write, Bash, Glob, Grep
5metadata:
6 source: https://skillmd.com/skills/giuseppe-trisciuoglio/unit-test-boundary-conditions
7---
8
9# Unit Testing Boundary Conditions and Edge Cases
10
11## Overview
12
13Systematic patterns for testing boundary conditions, corner cases, and limit values in Java using JUnit 5. Covers numeric boundaries, string edge cases, collection states, floating-point precision, date/time limits, and off-by-one scenarios.
14
15## When to Use
16
17- Numeric min/max limits, null/empty/whitespace inputs
18- Overflow/underflow validation, collection boundaries
19- Off-by-one errors, floating-point precision
20
21## Instructions
22
231. **Identify boundaries**: List numeric limits (MIN_VALUE, MAX_VALUE, zero), string states (null, empty, whitespace), collection sizes (0, 1, many)
242. **Apply parameterized tests**: Use `@ParameterizedTest` with `@ValueSource` or `@CsvSource` for multiple boundary values
253. **Test both sides of boundaries**: Cover values just below, at, and just above each boundary
264. **Run tests after adding each boundary category** to catch issues early
275. **Verify floating-point precision**: Use `isCloseTo(expected, within(tolerance))` with AssertJ
286. **Test collection states**: Explicitly test empty (0), single (1), and many (>1) element scenarios
297. **Handle overflow/underflow**: Use `Math.addExact()` and `Math.subtractExact()` to detect arithmetic overflow
308. **Test date/time edges**: Verify leap years, month boundaries, timezone transitions
319. **Iterate based on failures**: When a boundary test fails, analyze the error to discover additional untested boundaries; add test cases for the newly discovered edge conditions
32
33## Examples
34
35Requires: `junit-jupiter`, `junit-jupiter-params`, `assertj-core`.
36
37## Integer Boundary Testing
38
39```java
40import org.junit.jupiter.params.ParameterizedTest;
41import org.junit.jupiter.params.provider.ValueSource;
42import static org.assertj.core.api.Assertions.*;
43
44class IntegerBoundaryTest {
45
46 @ParameterizedTest
47 @ValueSource(ints = {Integer.MIN_VALUE, Integer.MIN_VALUE + 1, 0, Integer.MAX_VALUE - 1, Integer.MAX_VALUE})
48 void shouldHandleIntegerBoundaries(int value) {
49 assertThat(value).isNotNull();
50 }
51
52 @Test
53 void shouldDetectIntegerOverflow() {
54 assertThatThrownBy(() -> Math.addExact(Integer.MAX_VALUE, 1))
55 .isInstanceOf(ArithmeticException.class);
56 }
57
58 @Test
59 void shouldDetectIntegerUnderflow() {
60 assertThatThrownBy(() -> Math.subtractExact(Integer.MIN_VALUE, 1))
61 .isInstanceOf(ArithmeticException.class);
62 }
63
64 @Test
65 void shouldHandleZeroEdge() {
66 int result = MathUtils.divide(0, 5);
67 assertThat(result).isZero();
68
69 assertThatThrownBy(() -> MathUtils.divide(5, 0))
70 .isInstanceOf(ArithmeticException.class);
71 }
72}
73```
74
75## String Boundary Testing
76
77```java
78import org.junit.jupiter.params.ParameterizedTest;
79import org.junit.jupiter.params.provider.ValueSource;
80
81class StringBoundaryTest {
82
83 @ParameterizedTest
84 @ValueSource(strings = {"", " ", " ", "\t", "\n"})
85 void shouldRejectEmptyAndWhitespace(String input) {
86 boolean result = StringUtils.isNotBlank(input);
87 assertThat(result).isFalse();
88 }
89
90 @Test
91 void shouldHandleNullString() {
92 String result = StringUtils.trim(null);
93 assertThat(result).isNull();
94 }
95
96 @Test
97 void shouldHandleSingleCharacter() {
98 assertThat(StringUtils.capitalize("a")).isEqualTo("A");
99 assertThat(StringUtils.trim("x")).isEqualTo("x");
100 }
101
102 @Test
103 void shouldHandleVeryLongString() {
104 String longString = "x".repeat(1000000);
105
106 assertThat(longString.length()).isEqualTo(1000000);
107 assertThat(StringUtils.isNotBlank(longString)).isTrue();
108 }
109}
110```
111
112## Collection Boundary Testing
113
114```java
115class CollectionBoundaryTest {
116
117 @Test
118 void shouldHandleEmptyList() {
119 List<String> empty = List.of();
120
121 assertThat(empty).isEmpty();
122 assertThat(CollectionUtils.first(empty)).isNull();
123 assertThat(CollectionUtils.count(empty)).isZero();
124 }
125
126 @Test
127 void shouldHandleSingleElementList() {
128 List<String> single = List.of("only");
129
130 assertThat(single).hasSize(1);
131 assertThat(CollectionUtils.first(single)).isEqualTo("only");
132 assertThat(CollectionUtils.last(single)).isEqualTo("only");
133 }
134
135 @Test
136 void shouldHandleLargeList() {
137 List<Integer> large = new ArrayList<>();
138 for (int i = 0; i < 100000; i++) {
139 large.add(i);
140 }
141
142 assertThat(large).hasSize(100000);
143 assertThat(CollectionUtils.first(large)).isZero();
144 assertThat(CollectionUtils.last(large)).isEqualTo(99999);
145 }
146
147 @Test
148 void shouldHandleNullInCollection() {
149 List<String> withNull = new ArrayList<>(List.of("a", null, "c"));
150
151 assertThat(withNull).contains(null);
152 assertThat(CollectionUtils.filterNonNull(withNull)).hasSize(2);
153 }
154}
155```
156
157## Floating-Point Boundary Testing
158
159```java
160class FloatingPointBoundaryTest {
161
162 @Test
163 void shouldHandleFloatingPointPrecision() {
164 double result = 0.1 + 0.2;
165 assertThat(result).isCloseTo(0.3, within(0.0001));
166 }
167
168 @Test
169 void shouldHandleSpecialFloatingPointValues() {
170 assertThat(Double.POSITIVE_INFINITY).isGreaterThan(Double.MAX_VALUE);
171 assertThat(Double.NEGATIVE_INFINITY).isLessThan(Double.MIN_VALUE);
172 assertThat(Double.NaN).isNotEqualTo(Double.NaN);
173 }
174
175 @Test
176 void shouldHandleZeroInDivision() {
177 assertThat(1.0 / 0.0).isEqualTo(Double.POSITIVE_INFINITY);
178 assertThat(-1.0 / 0.0).isEqualTo(Double.NEGATIVE_INFINITY);
179 assertThat(0.0 / 0.0).isNaN();
180 }
181}
182```
183
184## Date/Time Boundary Testing
185
186```java
187class DateTimeBoundaryTest {
188
189 @Test
190 void shouldHandleMinAndMaxDates() {
191 LocalDate min = LocalDate.MIN;
192 LocalDate max = LocalDate.MAX;
193
194 assertThat(min).isBefore(max);
195 assertThat(DateUtils.isValid(min)).isTrue();
196 assertThat(DateUtils.isValid(max)).isTrue();
197 }
198
199 @Test
200 void shouldHandleLeapYearBoundary() {
201 LocalDate leapYearEnd = LocalDate.of(2024, 2, 29);
202 assertThat(leapYearEnd).isNotNull();
203 }
204
205 @Test
206 void shouldRejectInvalidDateInNonLeapYear() {
207 assertThatThrownBy(() -> LocalDate.of(2023, 2, 29))
208 .isInstanceOf(DateTimeException.class);
209 }
210}
211```
212
213## Array Index Boundary Testing
214
215```java
216class ArrayBoundaryTest {
217
218 @Test
219 void shouldHandleFirstElementAccess() {
220 int[] array = {1, 2, 3, 4, 5};
221 assertThat(array[0]).isEqualTo(1);
222 }
223
224 @Test
225 void shouldHandleLastElementAccess() {
226 int[] array = {1, 2, 3, 4, 5};
227 assertThat(array[array.length - 1]).isEqualTo(5);
228 }
229
230 @Test
231 void shouldThrowOnNegativeIndex() {
232 int[] array = {1, 2, 3};
233 assertThatThrownBy(() -> array[-1])
234 .isInstanceOf(ArrayIndexOutOfBoundsException.class);
235 }
236
237 @Test
238 void shouldThrowOnOutOfBoundsIndex() {
239 int[] array = {1, 2, 3};
240 assertThatThrownBy(() -> array[10])
241 .isInstanceOf(ArrayIndexOutOfBoundsException.class);
242 }
243
244 @Test
245 void shouldHandleEmptyArray() {
246 int[] empty = {};
247 assertThat(empty.length).isZero();
248 assertThatThrownBy(() -> empty[0])
249 .isInstanceOf(ArrayIndexOutOfBoundsException.class);
250 }
251}
252```
253
254## Best Practices
255
256- **Test at boundaries explicitly**: don't rely on random testing
257- **Test null and empty separately** from valid inputs
258- **Use parameterized tests** for multiple boundary cases
259- **Test both sides of boundaries** (just below, at, just above)
260- **Verify error messages** for invalid boundary inputs
261- **Document why** specific boundaries matter for your domain
262- **Test overflow/underflow** for all numeric operations
263
264## Constraints and Warnings
265
266- **Integer overflow**: Use `Math.addExact()` to detect silent overflow
267- **Floating-point precision**: Never use exact equality; always use tolerance-based assertions
268- **NaN behavior**: `NaN != NaN`; use `Float.isNaN()` or `Double.isNaN()`
269- **Collection size limits**: Be mindful of memory with large test collections
270- **String encoding**: Test with Unicode characters for internationalization
271- **Date/time boundaries**: Account for timezone transitions and daylight saving
272- **Array indexing**: Always test index 0, length-1, and out-of-bounds
273
274## References
275
276- [Integer.MIN_VALUE/MAX_VALUE](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html)
277- [Double.MIN_VALUE/MAX_VALUE](https://docs.oracle.com/javase/8/docs/api/java/lang/Double.html)
278- [AssertJ Floating Point](https://assertj.github.io/assertj-core-features-highlight.html#assertions-on-numbers)
279- [Boundary Value Analysis](https://en.wikipedia.org/wiki/Boundary-value_analysis)
280- [references/concurrent-testing.md](references/concurrent-testing.md) - Thread safety patterns
281- [references/parameterized-patterns.md](references/parameterized-patterns.md) - Off-by-one and parameterized examples