Java Unit testing with JUnit

The mechanics, and the reason most test suites become a maintenance cost instead of a safety net.

3 concepts · 9 interview questions

What this topic covers

Every concept in unit testing with junit, and the questions each one gets asked as. Where a question links, it has a full write-up.

JUnit 5 mechanics

Lifecycle callbacks, assertions, assumptions and parameterised tests. Knowing the lifecycle explains most surprising shared-state failures between tests.

  • What changed between JUnit 4 and JUnit 5?
  • When does a new test instance get created, and why does that matter?
  • What is a parameterised test, and when does it beat a loop?

Assertions and failure messages

A test's value at 3am is the message it prints when it fails. An assertion that only says false is a test you will have to debug before you can use it.

  • What makes a good assertion failure message?
  • How do you assert that a method throws?
  • Should one test have several assertions?

Structure and naming

Arrange, act, assert is a reading aid rather than a rule. A test name should say the behaviour, because the name is what appears in a failing build.

  • How should a test be named?
  • What is the arrange-act-assert pattern for?
  • How much setup is too much in a test?

More in Testing

See the whole reference map →