Practice: TDD
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
You know the cycle, the boundaries and how to change a rule. Now practise on small rules a shop really needs, from the test list to the last green test, and learn to spot a list that misses the edges.
Kata 1: password strength
ShopLite rates a password at sign-up. Start from the test list and let each boundary pair drive the code.
Example 1 · Password strength, driven by its test list
public class PasswordStrengthKata { static String strength(String password) { if (password == null) { throw new IllegalArgumentException("Password is required"); } if (password.length() >= 12 && hasUpper(password) && hasLower(password) && hasDigit(password) && hasSymbol(password)) { return "STRONG"; } if (password.length() >= 8 && hasLetter(password) && hasDigit(password)) { return "MEDIUM"; } return "WEAK"; }
static boolean hasUpper(String s) { return s.chars().anyMatch(Character::isUpperCase); } static boolean hasLower(String s) { return s.chars().anyMatch(Character::isLowerCase); } static boolean hasLetter(String s) { return s.chars().anyMatch(Character::isLetter); } static boolean hasDigit(String s) { return s.chars().anyMatch(Character::isDigit); } static boolean hasSymbol(String s) { return s.chars().anyMatch(ch -> !Character.isLetterOrDigit(ch)); }
static void check(String name, String expected, String actual) { System.out.println((expected.equals(actual) ? "PASS " : "FAIL ") + name + (expected.equals(actual) ? "" : ": expected " + expected + " but was " + actual)); }
public static void main(String[] args) { check("7 characters is weak", "WEAK", strength("abc1234")); check("8 characters with letters and digits is medium", "MEDIUM", strength("abcd1234")); check("8 letters only is weak", "WEAK", strength("abcdefgh")); check("11 characters, all kinds, is only medium", "MEDIUM", strength("Shop@lite12")); check("12 characters, all kinds, is strong", "STRONG", strength("Shop@lite123")); check("12 characters without a symbol is medium", "MEDIUM", strength("Shoplite1234")); try { strength(null); System.out.println("FAIL null is rejected"); } catch (IllegalArgumentException e) { System.out.println("PASS null is rejected"); } }}PASS 7 characters is weak PASS 8 characters with letters and digits is medium PASS 8 letters only is weak PASS 11 characters, all kinds, is only medium PASS 12 characters, all kinds, is strong PASS 12 characters without a symbol is medium PASS null is rejected
What this code does
- The tests come in boundary pairs: 7 and 8 characters, 11 and 12 characters, and a 12-character password with one kind of character missing. Each pair pins down exactly where a rule starts.
- The small
has...methods came from the refactor step, after the STRONG test turned green with one long condition.
Fewer than 8 characters is WEAK. 8 or more with at least one letter and one digit is MEDIUM. 12 or more with an upper-case letter, a lower-case letter, a digit and a symbol is STRONG. Anything else is WEAK, and null is rejected.
Kata 2: shipping cost by weight
A started kilogram is any part of a kilogram, which the courier charges as a whole kilogram. In code, (grams + 999) / 1000 rounds up.
ShopLite's courier charges by weight, so every number in the price list is a boundary. The table below tests both sides of each number.
Example 2 · Shipping cost: the boundaries around every number in the rule
class Shipping { // Up to 500 g: Rs 40. Up to 2000 g: Rs 70. Above 2000 g: Rs 70 + Rs 20 for every started extra kg. static int cost(int grams) { if (grams <= 0) throw new IllegalArgumentException("Weight must be positive: " + grams); if (grams <= 500) return 40; if (grams <= 2000) return 70; int extraGrams = grams - 2000; int extraKgStarted = (extraGrams + 999) / 1000; return 70 + 20 * extraKgStarted; }}
public class ShippingKata { public static void main(String[] args) { int[][] table = { {1, 40}, {500, 40}, {501, 70}, {2000, 70}, {2001, 90}, {3000, 90}, {3001, 110}, {10000, 230}, }; for (int[] row : table) { int actual = Shipping.cost(row[0]); System.out.printf("%5d g -> Rs %3d %s%n", row[0], actual, actual == row[1] ? "PASS" : "FAIL expected " + row[1]); } try { Shipping.cost(0); } catch (IllegalArgumentException e) { System.out.println(" 0 g -> rejected: " + e.getMessage()); } }} 1 g -> Rs 40 PASS
500 g -> Rs 40 PASS
501 g -> Rs 70 PASS
2000 g -> Rs 70 PASS
2001 g -> Rs 90 PASS
3000 g -> Rs 90 PASS
3001 g -> Rs 110 PASS
10000 g -> Rs 230 PASS
0 g -> rejected: Weight must be positive: 0What this code does
- Every number in the rule (500, 2000, and each extra kg) has its two sides tested.
(extraGrams + 999) / 1000rounds a started kilogram up: 1 g extra and 1000 g extra both count as 1 kg, 1001 g extra as 2. - 10000 g is a far-away value (8 extra kg: 70 + 160) and 0 g the invalid edge. Together the rows describe the courier's price list completely.
Up to 500 g costs Rs 40, up to 2000 g Rs 70, and above 2000 g Rs 70 plus Rs 20 for every started extra kilogram, so 2001 g already pays for one extra kg. Weights of 0 or less are rejected.
Kata 3: leap years
A year is a leap year if it is divisible by 4, except centuries, which count only if divisible by 400. Each exception arrives through one new failing test.
Example 3 · Leap years: three versions, three new tests
import java.util.LinkedHashMap;import java.util.Map;import java.util.function.IntPredicate;
public class LeapYearKata { public static void main(String[] args) { int[] years = {2024, 2023, 1900, 2000, 2100}; boolean[] expected = {true, false, false, true, false};
Map<String, IntPredicate> versions = new LinkedHashMap<>(); versions.put("v1 every 4 years ", y -> y % 4 == 0); versions.put("v2 not centuries ", y -> y % 4 == 0 && y % 100 != 0); versions.put("v3 unless by 400 ", y -> (y % 4 == 0 && y % 100 != 0) || y % 400 == 0);
System.out.println(" 2024 2023 1900 2000 2100"); for (Map.Entry<String, IntPredicate> v : versions.entrySet()) { StringBuilder line = new StringBuilder(v.getKey()); for (int i = 0; i < years.length; i++) { line.append(v.getValue().test(years[i]) == expected[i] ? " ok " : " RED "); } System.out.println(line); } }}2024 2023 1900 2000 2100 v1 every 4 years ok ok RED ok RED v2 not centuries ok ok ok RED ok v3 unless by 400 ok ok ok ok ok
What this code does
- v1 passes the easy years and fails 1900 and 2100: those tests ask for the century rule. v2 fixes them but now fails 2000, which asks for the 400 rule. v3 passes everything.
- Each exception in the rule entered the code because one test went red, which is triangulation in its purest form.
So 2024 is a leap year, 2023 is not, 1900 is not and 2000 is. year % 4 == 0 passes the first tests, 1900 forces the century rule, and 2000 forces the 400 rule.
Fixing a test list that misses edge cases
A weak test list has only comfortable middle values and misses boundaries, invalid input and extreme values, so buggy code can pass all of it.
A weak list has only middle values. This example runs a weak list and a boundary list against the same buggy shipping code.
Example 4 · A weak test list lets a bug through; boundaries catch it
class BuggyShipping { static int cost(int grams) { if (grams <= 500) return 40; if (grams <= 2000) return 70; return 70 + 20 * ((grams - 2000) / 1000); // bug: rounds a started kg down }}
public class WeakTestList { static void run(String label, int[][] table) { int failed = 0; StringBuilder reds = new StringBuilder(); for (int[] row : table) { int actual = BuggyShipping.cost(row[0]); if (actual != row[1]) { failed++; reds.append(" ").append(row[0]).append("g(expected ").append(row[1]).append(", got ").append(actual).append(")"); } } System.out.println(label + ": " + (table.length - failed) + " of " + table.length + " pass" + reds); }
public static void main(String[] args) { run("weak list ", new int[][] { {300, 40}, {1000, 70}, {5000, 130} }); run("boundary list", new int[][] { {500, 40}, {501, 70}, {2000, 70}, {2001, 90}, {3000, 90}, {3001, 110} }); }}weak list : 3 of 3 pass boundary list: 4 of 6 pass 2001g(expected 90, got 70) 3001g(expected 110, got 90)
What this code does
- 300 g, 1 kg and 5 kg are all comfortable middle values, and 5000 g happens to be a whole number of extra kilograms, so the rounding bug is invisible. The code "passes its tests" and ships.
- The boundary list adds the values right after each kilogram (2001 g, 3001 g) and the bug appears at once: a started kilogram must be charged in full.
To fix a list, go through the rule sentence by sentence, mark every number in it, and add the values on both sides of each, plus the invalid and extreme inputs.
If the code was written from the weak list, the new boundary rows are often the first red tests it has ever seen.
Finish up
Mark complete & continue
Next: Mini project: ShopLite coupon rules with TDD