Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 29 ยท Practice and review

Practice: Exercises with Solutions

Twelve graded JUnit and TestNG exercises with full solutions: assertions, exceptions, parameterized tests, nesting, dynamic tests, clocks, soft asserts and groups.

Reading about tests teaches you what the annotations are. Writing tests teaches you when to use them. This lesson gives you twelve exercises in three levels. Try each one on your own first, in the editor, before you open the solution below it. A test you wrote yourself, even a wrong one, teaches more than a correct test you only read.

How the lesson is organized: levels 1 and 2 use the real JUnit 6 API on our Java runner, with the same small run(...) helper as in Your First JUnit Test in place of Maven or your IDE. Level 3 covers TestNG ideas, which cannot run here, so those exercises ask you to build small JavaScript stand-ins that behave like the TestNG feature. Each stand-in says what it imitates.

Three levels

Level 1 Assertions, exceptions, delta, assertAll.
Level 2 Parameterized, nested, dynamic, clocks.
Level 3 TestNG ideas as stand-ins.

Attempt first. Then compare with the solution.

1 / 2

Level 1: assertions

Exercise 1: leap years. A year is a leap year if it is divisible by 4, except years divisible by 100, unless they are also divisible by 400. Write one test that covers an ordinary leap year, a century that is not a leap year, a century that is, and a common year.

Exercise 2: an exception with a message. Account.withdraw(amount) throws IllegalStateException with the text insufficient funds: balance 50, requested 80 when the balance is too low. Test the exception type and the message, and check that the balance did not change.

Exercise 3: report every wrong field. Person.parse("Ada Lovelace,36") returns a record with first name, last name and age. Write a test that checks all three fields and reports all mismatches in one run, not just the first.

Exercise 4: floating point. Convert Celsius to Fahrenheit. Test 37 degrees against 98.6 without writing a test that fails because of rounding noise.

Solutions for level 1

Java Level 1 solutions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Why these solutions look the way they do:

  • Exercise 1 puts four cases in one test because they are four facts about one rule. The message argument (third parameter of assertTrue) makes a failure self-explanatory. Splitting into four methods is equally valid; Designing Good Tests discusses the trade-off.
  • Exercise 2 uses the return value of assertThrows. Checking the type alone would pass for any IllegalStateException; checking the message pins down which problem occurred. The balance check proves the failed call had no side effect.
  • Exercise 3 needs assertAll. Without it, the first failing assertEquals stops the test and hides the others. Try changing the expected age and the last name at once to see both reported.
  • Exercise 4: 37 * 9 / 5 + 32 is not exactly 98.6 in binary floating point, so an exact comparison may fail. The third argument is the allowed difference. Use a delta of 0.0 only when the value is exactly representable.

Level 2: structure and reuse

Exercise 5: fizz buzz table. fizzBuzz(n) returns "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for both and the number as text otherwise. Test the cases 1, 3, 5, 7 and 15 with one test method.

Exercise 6: a stack in two situations. For an IntStack with push, pop, peek and isEmpty, group tests into "when empty" and "with two items" using nested classes, so that the shared set-up is written once. pop on an empty stack throws IllegalStateException.

Exercise 7: tests generated from data. slugify("Hello World") returns hello-world. Generate one named test per input and expected value from a list, but through @TestFactory rather than @ParameterizedTest.

Exercise 8: a test that depends on the time of day. Greeter.greeting() returns Good morning before noon and Good afternoon after. Make the class testable without waiting for the clock, and test both sides of noon.

Solutions for level 2

Java Level 2 solutions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notes on the design:

  • Exercise 5: @CsvSource turns each row into one invocation, and name = "..." makes the report read like the table. See Parameterized and Dynamic Tests for sources and converters.
  • Exercise 6: @Nested classes must be non-static inner classes, so they can read the outer stack field. For a test in WithTwoItems, JUnit runs the outer @BeforeEach first and the inner one second, on a fresh outer instance each time.
  • Exercise 7: a @TestFactory method returns tests as data (DynamicTest). Unlike @ParameterizedTest, you can compute the list in plain Java, which is handy when cases come from a file. Dynamic tests do not get the per-test @BeforeEach treatment, only the factory method does (Lifecycle, Nested Tests and Display Names).
  • Exercise 8: the fix is to inject the clock instead of calling Instant.now() inside the class. Clock.fixed then freezes time. This is the same cure used for flaky time-based tests in Flaky Tests and Common Mistakes.

Level 3: TestNG ideas

TestNG cannot run on this site, so the exercises below ask for a small JavaScript stand-in of a TestNG feature. Writing the stand-in teaches the behavior; the real library does the same with annotations and testng.xml.

Exercise 9: soft assertions. Build a SoftAssert class. assertEquals(actual, expected, label) records a failure and keeps going. assertAll() throws one error that lists every recorded failure. (TestNG's SoftAssert works like this: remember to call assertAll() at the end or nothing fails.)

Exercise 10: group filtering. Write select(tests, include, exclude). A test is selected when its groups share a name with include (an empty include list means everything) and share no name with exclude. Exclusion wins when both match.

Exercise 11: dependent tests. Write a runner where a test with dependsOn: [...] is skipped when any dependency did not pass, as with TestNG's dependsOnMethods. A skipped test is not a failure, but its cause should be visible.

Exercise 12: named data-provider rows. Given a test name and rows of arguments, produce one test per row named like parseAge[1]("abc"), so a failing row can be found by its inputs.

Solutions for level 3

JS Level 3 solutions, part 1

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Level 3 solutions, part 2

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last two rows of exercise 12 fail on purpose: parseAge throws a RangeError for "abc" and "-1", and the test body does not expect it. Read the row names and the problem is clear without opening the code. In exercise 11, login is the only real failure; readProfile and closeAll are skipped because something they depend on did not pass, while readSettings still runs.

What to take from level 3:

  • Soft assertions are best for checking many independent fields of one response. They are the wrong tool when later steps need earlier ones to hold (do not read element 0 after a soft check that the list is non-empty).
  • Exclusion beats inclusion in group selection, which is how TestNG behaves when a method is in both an included and an excluded group.
  • Skipped is not failed. A dependsOnMethods chain reports one real failure and a trail of skips. It also means one broken test can hide the state of many others, which is why Dependencies, Priority and Test Ordering calls heavy use of dependencies a smell.
  • Row names with inputs turn "test 3 failed" into a clue. TestNG indexes the invocations of a data provider, and JUnit's name = "..." serves the same purpose.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does exercise 3 use assertAll instead of three plain assertEquals calls?

    An assertion failure throws, ending the test. assertAll runs every check and then reports all failures together.
  2. 2. What is the cleanest way to test a class that asks for the current time?

    Passing the clock in makes time an input, so the test can freeze it. Sleeping or changing the system date makes tests slow and flaky.
  3. 3. In a @Nested test class, which set-up methods run for a test in the inner class?

    Each nested level adds context. The outer set-up runs first on the outer instance, then the inner one.
  4. 4. A TestNG test with dependsOnMethods whose dependency failed is reported as...

    TestNG skips dependents rather than failing them, so the report shows one root cause and a list of skipped tests.

Summary

  • Pin down exception type and message, and check state afterwards, with assertThrows.
  • Use assertAll (JUnit) or soft assertions (TestNG) to see every wrong field at once.
  • Floating-point comparisons need a delta.
  • @ParameterizedTest and @TestFactory both generate tests from data; the first is declarative, the second is plain Java code.
  • @Nested shares set-up between related situations; inject a Clock to test time-dependent code.
  • TestNG's groups, dependencies and data providers are easy to imitate in small stand-ins, which is a good way to learn what the real feature promises.

Next: JUnit and TestNG Interview Questions, forty questions with short, accurate answers.