Enums and nulls

An enum is a list of cases that the compiler already knows, so a test of every constant writes itself. @EnumSource supplies the constants, @NullSource supplies one null, and both are parameterised tests with one parameter. This lesson runs three methods over a three-constant enum and a null.

@EnumSource

@EnumSource(Size.class) runs the method once for every constant of the enum, in declaration order. The parameter type is the enum, so the method can call its methods without a cast.

import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.NullSource; public class EnumTest { enum Size { SMALL, MEDIUM, LARGE } @ParameterizedTest @EnumSource(Size.class) void everySizeHasAName(Size size) { assertNotNull(size.name()); } @ParameterizedTest @EnumSource(value = Size.class, names = {"SMALL", "MEDIUM"}) void onlyTheSmallSizes(Size size) { assertNotNull(size); } @ParameterizedTest @NullSource void nullIsAllowed(String value) { assertNull(value); } }

Include and exclude names

The names attribute selects constants by name, and its default mode is INCLUDE: the listed names are the cases. Set mode = EnumSource.Mode.EXCLUDE and the list becomes the constants to leave out, which is shorter when the enum is long and the exception is one value. A name that does not exist fails the source with a clear message, which is better than a silently missing case.

A name can also be a regular expression with mode = EnumSource.Mode.MATCH_ALL or MATCH_ANY. That is useful for a naming convention, and a trap when the convention changes; a literal list is easier to audit.

@NullSource

@NullSource supplies exactly one null argument. The parameter must be an object type: an int cannot be null, and the source fails before the test runs. The matching assertion is usually assertNull, or a branch that expects a specific exception.

An empty value is a separate source, @EmptySource, which supplies an empty string, list, set or map. A method that treats null and empty differently needs both, and the two cases belong in the same parameterised method when the contract is one rule.

The report

javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out EnumTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors

Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│  └─ EnumTest ✔
│     ├─ nullIsAllowed(String) ✔
│     │  └─ [1] null ✔
│     ├─ everySizeHasAName(Size) ✔
│     │  ├─ [1] SMALL ✔
│     │  ├─ [2] MEDIUM ✔
│     │  └─ [3] LARGE ✔
│     └─ onlyTheSmallSizes(Size) ✔
│        ├─ [1] SMALL ✔
│        └─ [2] MEDIUM ✔
└─ JUnit Vintage ✔

Test run finished after 1207 ms
[         7 containers found      ]
[         0 containers skipped    ]
[         7 containers started    ]
[         0 containers aborted    ]
[         7 containers successful ]
[         0 containers failed     ]
[         6 tests found           ]
[         0 tests skipped         ]
[         6 tests started         ]
[         0 tests aborted         ]
[         6 tests successful      ]
[         0 tests failed          ]

Six invocations: three constants, two selected constants and one null. The containers are seven because each parameterised method is a container of its cases. The null case is named [1] null, which is the only place the value is visible; the type is on the method line.

What a source can supply

A source can supply as many arguments as the method has parameters, and the types must match after conversion. The enum source supplies one value of the enum, the null source one null, the empty source one empty value, and they can be combined with @NullAndEmptySource when a method must accept both. A method with two parameters needs a source that supplies two values, not two single sources.

Exercises

  1. Add a constant to the enum and run. Which counts change, and by how much?
  2. Change the include list to exclude LARGE and check that the second method still has two cases.
  3. Add @EmptySource beside @NullSource and run. How many cases does that method have now?
  4. Change the null method to take an int and read the launcher error.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many cases does @EnumSource(Size.class) supply for a three-constant enum?

    Answer

    3, one per constant in declaration order

    The default source includes every constant of the enum.

  2. What does @NullSource supply?

    Answer

    Exactly one null argument

    NullSource adds one case whose value is null; the parameter must be an object type.

  3. Which mode makes names a list of constants to leave out?

    Answer

    EnumSource.Mode.EXCLUDE

    INCLUDE is the default; EXCLUDE treats the names as the exceptions.

  4. What does this program print? public class Q1 { enum Size { SMALL, MEDIUM } public static void main(String[] args) { System.out.println(Size.values().length); } }

    Answer

    2

    values returns both constants, so the length is 2.

  5. What does this program print? public class Q2 { public static void main(String[] args) { String value = null; System.out.println(value == null); } }

    Answer

    true

    The variable holds null, so the comparison is true.

  6. What does this program print? public class Q3 { public static void main(String[] args) { System.out.println("SMALL".toLowerCase()); } }

    Answer

    small

    toLowerCase changes every letter to lower case.

  7. What does this program print? public class Q4 { public static void main(String[] args) { int[] values = {1, 2, 3}; System.out.println(values.length); } }

    Answer

    3

    The array has three elements, so length is 3.

  8. Why can a parameter supplied by @NullSource not be an int?

    Answer

    A primitive cannot hold null

    Null is a reference value; a primitive parameter has no way to hold it.

  9. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println(java.util.List.of("a", "b").size() + 1); } }

    Answer

    3

    The list has two elements, and 2 + 1 is 3.

  10. A method has two parameters. Which source fits it?

    Answer

    A source that supplies two values per case, such as @CsvSource

    The number of supplied values must match the number of parameters.

The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.

Article author: Arthur Isaev