QA AND TEST AUTOMATION · PART 2 · PROGRAMMING FOR TESTERS · JAVA · 24 OF 112

Java Exceptions and Streams for Test Automation

Two Java features test code leans on: exceptions (checked versus unchecked, try, catch and finally, try-with-resources, custom exceptions with clear messages, and why swallowing errors hides bugs) and streams with lambdas (filter, map, collect, count, sum, max, groupingBy, anyMatch and Optional), each run on ShopRung product data with the real results.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 14

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Checked vs unchecked
  • catch narrow, keep the cause
  • finally and try-with-resources
  • filter, map, collect, group

Notes

Exceptions

An exception is an object that says something went wrong, with a message and a stack trace that shows where. When it is thrown, normal flow stops and the exception travels up through the methods that called it, until some code catches it. In a test, an exception nobody catches makes the test end in error, and a failed assertion, which is itself an exception, makes it fail. Reading stack traces is a core skill for debugging tests.

What an exception is
  • an object that says "this
  • went wrong", with a message
  • and a stack trace
  • it travels up the call chain
  • until a catch handles it
  • in a test: an uncaught
  • exception = test ERROR
  • a failed assert = test FAIL

Two kinds

Java has two kinds. Checked exceptions, like an I O exception when a file is missing, must be caught or declared with throws, and the compiler enforces it. Unchecked exceptions extend runtime exception and usually mean a bug or bad input: null pointer, illegal argument, number format. You do not have to declare them. A third family, errors such as out of memory, are not meant to be caught at all. Interviewers often ask for this difference.

Checked vs unchecked
  • checked (extends Exception) the compiler makes you catch or declare: IOException, InterruptedException
  • unchecked (RuntimeException) bugs and bad input: NullPointerException, IllegalArgumentException, NumberFormatException
  • errors (Error): out of memory

try and catch

Use try and catch for code that may fail. This method reads a price text from the page and returns cents. Given dollar twenty four ninety nine, it returns two thousand four hundred ninety nine. Given the text abc, parse double throws a number format exception. We catch it and throw a new exception with a clear message, not a price, abc, passing the original as the cause. Now a failing test says exactly what text broke it.

Parse a price
static long cents(String text) {
  try {
    return Math.round(Double
      .parseDouble(text.replace(
        "$", "")) * 100);
  } catch (NumberFormatException e) {
    throw new IllegalArgumentException(
      "Not a price: " + text, e);
  }
}
// cents("$24.99") → 2499

finally and resources

A finally block runs whether the try part passed or threw, which is the place for clean up, like resetting ShopRung's data after a test. For anything that must be closed, like a file reader, a database connection or a browser, use try with resources: declare it in brackets after try, and Java closes it for you at the end, even on failure. Forgetting to close resources is how test suites leak browsers and slowly run out of memory.

Cleaning up
try {
  runCheckout();
} finally {
  api.post("/api/test/reset");
} // runs pass or fail

try (var reader = Files
    .newBufferedReader(path)) {
  ... read test data ...
} // reader closed for you

Custom exceptions

You can define your own exceptions by extending runtime exception. A name like coupon not applicable, with the shop's real message, says what went wrong before anyone opens the code. Frameworks do this too: Selenium has no such element exception and timeout exception, and Playwright has timeout errors. When a test fails, a precise name and message is half of the bug report already written.

A custom exception
class CouponNotApplicable
    extends RuntimeException {
  CouponNotApplicable(String m)
    { super(m); }
}
throw new CouponNotApplicable(
  "This coupon needs a subtotal
   of at least $50.00");

name + message = half the
bug report already written

Do not swallow

The worst thing test code can do is swallow an exception. Here, applying the coupon is wrapped in a catch of any exception that does nothing. If the coupon breaks, the test still passes, and the suite lies to everyone. Rules: catch the narrowest type you can actually handle, never leave a catch block empty, and either log and re throw, or re throw with more context. A test should fail loudly when the product is broken.

The worst catch
try {
  cart.applyCoupon("SAVE10");
} catch (Exception e) {
  // ignore   ← test now passes
}             //  even if broken

rules:
  catch the narrowest type
  never empty catch blocks
  log or re-throw with context

Streams

Now streams. A stream is a pipeline over a collection: a source, then steps, then one result. Take the twelve ShopRung products, filter the ones with zero stock, map each to its sku, and collect to a list. The answer is MG two oh two, the red mug. The arrow form, p arrow p dot stock, is a lambda: a small function written inline. Product colon colon sku is a method reference, a shorter way to write the same lambda.

Out-of-stock SKUs
List<String> out = products
  .stream()
  .filter(p -> p.stock() == 0)
  .map(Product::sku)
  .toList();
// [MG-202]

p -> ... is a lambda
Product::sku is a method
  reference (p -> p.sku())

Counting and sums

Streams answer questions in one line. How many products cost under ten dollars? Two, the sticker packs. What do all twelve cost together? Thirty nine thousand six hundred and ninety four cents. Which is the most expensive? The noise cancelling headphones. The three cheapest prices? Four ninety nine, four ninety nine and twelve fifty. In a test, these become assertions that compare the API's data with what the page shows.

Answers in one line
.filter(p -> p.price() < 1000)
  .count()                // 2
.mapToLong(Product::price)
  .sum()                  // 39694
.max(comparingLong(
  Product::price))
  → Noise-Cancelling Headphones
.map(Product::price).sorted()
  .limit(3).toList()
  // [499, 499, 1250]

Grouping and matching

Grouping by builds a map from a stream. Group products by category and count them: three books, two clothing, three electronics, two home and two stickers. That checks the category filter on the page in one assertion. All match checks a condition holds for every item, like no product has negative stock. Any match checks at least one does, like some product name contains mug. These read almost like the requirement itself.

Group and check
Map<String, Long> byCat =
  products.stream().collect(
    groupingBy(Product::category,
      TreeMap::new, counting()));
// {Books=3, Clothing=2,
//  Electronics=3, Home=2,
//  Stickers=2}

allMatch(p -> p.stock() >= 0)
                      // true
anyMatch(p -> name has "Mug")

Optional

Some stream results may not exist. Find first returns an Optional, a box that either holds a value or is empty, instead of null. Searching for a sku that does not exist gives an empty optional, so is present is false. Use map and or else to give a default, or or else throw when the value must be there, which fails with a clear exception instead of a null pointer three lines later.

Optional
Optional<Product> p = products
  .stream()
  .filter(x -> x.sku()
     .equals("XX-000"))
  .findFirst();
p.isPresent()          // false
p.map(Product::name)
 .orElse("none")
p.orElseThrow()   // throws
  NoSuchElementException

Common mistakes

Mistakes to avoid. Empty catch blocks. Catching exception for everything. Re throwing without passing the original cause, which loses the real stack trace. Adding thread sleep to hide a timing exception instead of waiting properly, which you will learn in Part five. Very long, clever stream chains nobody can debug; split them and name the steps. And calling get on an optional without checking it first.

Avoid these
  • empty catch blocks
  • catch (Exception e) for everything
  • losing the cause when re-throwing
  • Thread.sleep to "fix" timing exceptions
  • long, clever stream chains nobody can debug
  • Optional.get() without a check

Say it like this

In the interview: checked exceptions must be caught or declared, like an I O exception; unchecked ones extend runtime exception, like a null pointer, and usually mean bugs or bad input. Add how you use them: I catch narrow types, keep the cause when re throwing, use try with resources, and never swallow errors in tests. If asked for a stream, describe filter, map and collect, for example the skus of out of stock products from an API response.

In the interview
  • "Checked exceptions must be caught or declared, like
  • IOException; unchecked extend
  • RuntimeException, like NPE.
  • I catch narrow types, keep the cause, and never swallow errors
  • in tests. Streams: filter, map, collect, e.g. the SKUs of out-of-stock products from an API response."

Interview questions

Q1What is the difference between checked and unchecked exceptions?

Checked exceptions (subclasses of Exception but not RuntimeException) must be caught or declared, such as IOException. Unchecked exceptions (RuntimeException subclasses) need not be, such as NullPointerException or IllegalArgumentException.

Q2What is the difference between throw and throws?

throw raises an exception object inside a method; throws in a method signature declares which checked exceptions the method may pass to its caller.

Q3What is try-with-resources?

A try statement that declares resources implementing AutoCloseable; Java closes them automatically at the end, even if an exception is thrown.

Q4Does finally always run?

Almost always: after try and catch, whether or not an exception was thrown, except in cases like System.exit() or a JVM crash.

Q5Why is an empty catch block dangerous in a test?

It hides failures, so the test passes even when the product is broken. Tests should fail loudly with a clear message.

Q6What is a lambda and a method reference?

A lambda is an inline function such as p -> p.stock() == 0; a method reference such as Product::sku is a shorter form of a lambda that just calls one method.

Q7Write a stream that counts products per category.

products.stream().collect(Collectors.groupingBy(Product::category, Collectors.counting()));

Q8What is Optional for?

To represent a value that may be absent without using null, with methods like isPresent, map, orElse and orElseThrow.