Skip to the page

Mobile, performance and coding · mid

Writing and reviewing unit tests

A test that cannot fail proves nothing. Parameterised tests with the right boundary values are strong, and a reviewer can spot weak ones fast.

The notes

What you must know

  • Indian number grouping: the last three digits, then groups of two (1,000; 10,000; 1,00,000; 1,00,00,000). The boundaries are where a comma appears.
  • Good cases for a currency formatter in paise: 0, 1, 99, 100, 99999, 100000, 9999999, 10000000, a large number, and a negative.
  • Use one @ParameterizedTest with @CsvSource. Expected strings with commas need a custom delimiter or quotes. Use name = "{0} paise -> {1}" for readable failures.
  • Never use double for money. Use integers (paise) or BigDecimal.
  • Review a weak test: a shared static object makes tests depend on order. Create a new object per test in @BeforeEach.
  • assertTrue(total() > 0) passes for almost any wrong total. Assert the exact value.
  • assertEquals takes expected first, then actual. Reversed arguments give misleading messages.
  • A try/catch that prints the exception makes the test pass when the code throws. Let the exception fail the test, or assert it on purpose with assertThrows.

The red pen

Common traps: mistake → fix

  • Mistake: Testing one big number is enough

    Fix: test the boundaries where commas appear.

  • Mistake: static is fine because the tests pass

    Fix: they pass only in the current order.

  • Mistake: assertContains("₹") is a test of format

    Fix: it passes for almost any output.

Easy to hard

Questions interviewers ask, easy to hard

  1. Write unit tests for an Indian currency formatter. Which values do you pick?
  2. Review this test: shared static cart, assertTrue(total > 0), and a try/catch with println.
  3. Why is assertEquals(actual, expected) a problem?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview