Example tests check specific answers. Property checks test a relationship that should hold across many inputs, such as “sorting preserves size” or “normalizing twice equals normalizing once.” They complement boundary examples; they do not prove every possible program behavior.
Understand the contract
A property must follow from the contract. Sorting should preserve the multiset of entries, not necessarily the original order. A total over concatenated lists should equal the sum of their separate totals when arithmetic does not overflow. State the conditions under which the property is valid before generating inputs.
new Random(seed) gives a repeatable sequence for this Java generator. nextInt(bound) returns an integer from zero inclusive to bound exclusive; the bound must be positive. Use a fixed seed and include the case index or input in a failure message so the failure can be reproduced. The sequence is for tests, not security-sensitive randomness.
A generated test can still have a weak oracle. Checking only output size would allow a sort that replaces every value with zero. Compare with a simple independent reference implementation or combine several properties. Keep explicit edge cases even when generating random values, because random sampling may never reach the important boundary.
Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random first = new Random(17);
Random second = new Random(17);
boolean same = true;
for (int index = 0; index < 20; index++) {
if (first.nextInt(100) != second.nextInt(100)) {
same = false;
}
}
System.out.println(same);
}
}Check your prediction
trueTrace a different case
The contract promised above is a concatenation law: for any lists a and b,
total(a ++ b) == total(a) + total(b), where ++ means "a followed by b".
The generator below makes lists of 0 to 4 values, so empty lists appear on
either side, and keeps values below 100 so int overflow cannot interfere. The
expected value is built from two separate totals, not from the joined list, so
the check does not reuse the code under test to compute its own answer.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random(17);
for (int index = 0; index < 50; index++) {
List<Integer> a = randomList(random);
List<Integer> b = randomList(random);
List<Integer> joined = new ArrayList<>(a);
joined.addAll(b);
if (total(joined) != total(a) + total(b)) {
throw new AssertionError("case " + index + ": " + a + " ++ " + b);
}
}
System.out.println("50 cases passed");
System.out.println(total(List.of()));
}
static List<Integer> randomList(Random random) {
List<Integer> values = new ArrayList<>();
int size = random.nextInt(5);
for (int item = 0; item < size; item++) {
values.add(random.nextInt(100));
}
return values;
}
static int total(List<Integer> values) {
int total = 0;
for (int value : values) {
total += value;
}
return total;
}
}Check your prediction
50 cases passed
0Try breaking total so it skips the first element (start the loop at index 1
with a counted for loop). The law fails on the first generated case where both
lists are nonempty: the joined total drops only a's first value, while
total(a) + total(b) drops b's first value as well. Cases with an empty a still
pass, which is why the generator must produce both kinds. The second line is the explicit edge case: a property
says how totals relate, but only an example pins the empty total to 0.
Look for a wrong implementation that still satisfies the property
Idempotence says applying an operation twice agrees with applying it once. A function always returning an empty String satisfies that relationship, so it cannot alone prove useful normalization. Pair the property with independent expected examples that reject that constant implementation.
For a sorted report, size preservation is also insufficient: replacing every value with zero preserves size. Combine membership preservation, order checks and a small independent reference when those are part of the contract. Choose properties whose assumptions match the generated input domain.
A fixed seed makes a failure reproducible; it does not make sampling exhaustive. Preserve boundary cases outside the generator and save a minimal explicit regression input when a generated case reveals a defect. The smaller example will be easier for the next reader to understand.
Debug a plausible mistake
A property check is only as strong as its generator. If the generated inputs never reach the case where the implementation is wrong, 50 passing cases are 50 copies of the same evidence.
Strengthen a weak generator
normalize must remove all leading and trailing spaces, so the property is
normalize(spaces + core + spaces).equals(core). The check below passes, yet
normalize is wrong. Predict what it prints, then read normalize and find an
input it gets wrong. Change the generator first, until the check fails and the
message shows a failing input. Only then repair normalize, and keep the stronger
generator. The supplied version compiles; its behavior is the problem.
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random(17);
for (int index = 0; index < 50; index++) {
String core = "Item" + random.nextInt(100);
String input = " " + core + " ";
if (!normalize(input).equals(core)) {
throw new AssertionError("case " + index + ": [" + input + "]");
}
}
System.out.println("50 cases passed");
}
static String normalize(String text) {
String result = text;
if (result.startsWith(" ")) {
result = result.substring(1);
}
if (result.endsWith(" ")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
}Hint 1: the idea
Every generated input has exactly one space on each side, and that is the one amount of padding this normalize handles. The digits vary, but the property is about spaces. Zero spaces and two or more spaces are never tried.
Hint 2: a first step
Let the generator choose the padding too, over a small range that includes no spaces and more than one space on each side. Run it and read the failing case before you change normalize.
Show one solution
With the padding generated, the unchanged normalize fails on the first case:
Exception in thread "main" java.lang.AssertionError: case 0: [ Item76 ]Then the repair:
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random(17);
for (int index = 0; index < 50; index++) {
String core = "Item" + random.nextInt(100);
String input = " ".repeat(random.nextInt(4)) + core + " ".repeat(random.nextInt(4));
if (!normalize(input).equals(core)) {
throw new AssertionError("case " + index + ": [" + input + "]");
}
}
System.out.println("50 cases passed");
}
static String normalize(String text) {
return text.trim();
}
}Expected output after repair:
50 cases passedThree leading spaces leave two behind after the single substring(1), so the
property fails as soon as the padding varies. The generator change is the main
fix: it is what turned a check that could never fail into one that can. Counts
from 0 also cover input with no padding at all, which an implementation that
always cuts one character would get wrong.
Build it yourself
Properties & Seeded Cases: practice
Write sortedCopy(List<Integer>), which returns a new sorted list and leaves its
argument unchanged. Test it with 60 generated lists from new Random(29): sizes
0 to 5 and values 0 to 9, so empty lists and duplicates both occur. For every
case check four properties: same size, each element no larger than the next,
every value appears as many times as in the source, and the source is unchanged.
Add one known example, [3, 1, 3] gives [1, 3, 3]. Print Sort properties passed.
Before you write it, name a wrong sortedCopy that passes the size check alone, and one that passes size and order but fails the counts.
public class Main {
public static void main(String[] args) {
// Generate cases, check the four properties, then the known example.
System.out.println("Your workspace");
}
}Hint 1: the idea
No single property defines sorting. "Same size" allows a list of zeros, "in order" allows a list of zeros too, and only counting each value rules them out. Together, they describe a sort.
Hint 2: a first step
Write the generator loop first and print a few lists to see empty and duplicate
cases. Collections.frequency(list, value) counts how often a value appears.
Take a List.copyOf snapshot of the source before calling sortedCopy.
Show one solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random random = new Random(29);
for (int index = 0; index < 60; index++) {
List<Integer> source = new ArrayList<>();
int size = random.nextInt(6);
for (int item = 0; item < size; item++) {
source.add(random.nextInt(10));
}
List<Integer> before = List.copyOf(source);
List<Integer> sorted = sortedCopy(source);
String label = "case " + index + ": " + source;
check(label + " size", sorted.size() == source.size());
for (int position = 1; position < sorted.size(); position++) {
check(label + " order", sorted.get(position - 1) <= sorted.get(position));
}
for (int value : source) {
check(label + " count of " + value,
Collections.frequency(sorted, value) == Collections.frequency(source, value));
}
check(label + " source", source.equals(before));
}
check("known", sortedCopy(List.of(3, 1, 3)).equals(List.of(1, 3, 3)));
System.out.println("Sort properties passed");
}
static List<Integer> sortedCopy(List<Integer> values) {
List<Integer> copy = new ArrayList<>(values);
Collections.sort(copy);
return copy;
}
static void check(String name, boolean condition) {
if (!condition) {
throw new AssertionError(name);
}
}
}Expected output:
Sort properties passedValues below 10 in lists of up to five make duplicates common, so the count
property is really exercised. Returning List.of(0, 0, 0) of the right size
passes the size and order checks but fails the counts. The label puts the case
number and source list in every failure, so a failure can be copied into an
explicit regression test. The known example pins one exact answer that the
properties alone do not state.
Change it and test again
Make sortedCopy return a list of zeros with the source's size. Which property catches it, and which still hold? Then make it sort but drop duplicates with a TreeSet: which property fails now? Restore the real sort. Record the seed and a minimized failing input if a more complex generated test fails; a short regression example is easier to understand than replaying hundreds of cases.
Explain before moving on
What does a passing property check add beyond one example? What does it fail to prove? Explain why reproducibility matters and why randomized tests should not depend on the current time for their seed during routine regression checks.
Completion is saved in this browser only. It does not measure mastery.