true, false, null and a message
Not every result is a number. A method can answer a question with a boolean, or return a value that may be absent with null. JUnit has four assertions for those two cases, and each takes an optional message that becomes part of the failure. This lesson uses all four on a small class.
The class and four tests
Flags.java answers two questions: whether a number is even, and what nickname a name has. An empty name has no nickname, so the method returns null.
public class Flags {
static boolean isEven(int n) {
return n % 2 == 0;
}
static String nickname(String name) {
if (name.isEmpty()) {
return null;
}
return name.toLowerCase();
}
}
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class FlagsTest {
@Test
void evenNumberIsEven() {
assertTrue(Flags.isEven(4), "4 should be even");
}
@Test
void oddNumberIsNotEven() {
assertFalse(Flags.isEven(7), "7 should be odd");
}
@Test
void emptyNameHasNoNickname() {
assertNull(Flags.nickname(""), "an empty name has no nickname");
}
@Test
void nameHasANickname() {
assertNotNull(Flags.nickname("Ada"), "Ada has a nickname");
}
}
assertTrue and assertFalse
assertTrue(condition) fails when the condition is false; assertFalse(condition) fails when it is true. The two are not redundant: the name of the assertion says what the test expects, and a reader of a red report sees expected: <true> but was: <false> only in the first case and the reverse in the second.
A boolean assertion is the right choice when the method returns a boolean, as isEven does. When the method returns a number, compare the number with assertEquals; a test that writes assertTrue(Flags.isEven(4)) is fine, but assertTrue(result == 4) hides the value the report could show.
assertNull and assertNotNull
assertNull(value) passes only when the value is null. It is the assertion for the absent case, and its partner assertNotNull(value) is the assertion for the case that must produce something. A test that calls a method and immediately calls another method on the result should use assertNotNull first: when the result is null, the second call throws a NullPointerException and the report shows an error instead of the missing value.
A returned null is a design choice. The alternative is an Optional or an exception, and both are easier to test than a null that every caller must remember. The Java course covers Optional in its streams part.
The message argument
Every assertion takes an optional last argument, the message. It is printed before the expected and actual values when the test fails. A good message says what the test believes and why, in the words of the domain: "4 should be even" tells the reader which rule broke, while "failed" adds nothing to the method name and the values.
The message is built only when the assertion fails, unless it is a Supplier<String>; a string literal costs nothing either way. In a parameterised test the message often names the case, which is the subject of lesson 016.
The report
javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out Flags.java FlagsTest.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 ✔
│ └─ FlagsTest ✔
│ ├─ emptyNameHasNoNickname() ✔
│ ├─ evenNumberIsEven() ✔
│ ├─ nameHasANickname() ✔
│ └─ oddNumberIsNotEven() ✔
└─ JUnit Vintage ✔
Test run finished after 559 ms
[ 4 containers found ]
[ 0 containers skipped ]
[ 4 containers started ]
[ 0 containers aborted ]
[ 4 containers successful ]
[ 0 containers failed ]
[ 4 tests found ]
[ 0 tests skipped ]
[ 4 tests started ]
[ 0 tests aborted ]
[ 4 tests successful ]
[ 0 tests failed ]
Exercises
- Make isEven return the opposite answer and run. Which message does the report print for the even test?
- Remove the message from one assertion, break the code, and compare the failure line with the one that had a message.
- Add a test for nickname("ADA") and decide whether the lower-case result is part of the contract.
- Change nickname to return an empty string instead of null and run. Which test fails, and with what message?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which assertion passes when the value is null?
Answer
assertNull
assertNull succeeds only for a null value; assertNotNull is its opposite.
-
What does the message argument of an assertion do?
Answer
It is printed with the failure, before the values
The message explains the rule that broke and appears only when the assertion fails.
-
Why use
assertNotNullbefore calling a method on a result?Answer
A null would throw a NullPointerException and hide the real failure
The null assertion reports the missing value; without it the next call throws and the report shows an error.
-
What does this program print?
public class Q1 { public static void main(String[] args) { System.out.println(4 % 2 == 0); } }Answer
true
4 divided by 2 leaves no remainder, so the comparison is true.
-
What does this program print?
public class Q2 { public static void main(String[] args) { System.out.println(7 % 2 == 0); } }Answer
false
7 divided by 2 leaves a remainder of 1, so the number is not even.
-
What does this program print?
public class Q3 { public static void main(String[] args) { String name = ""; System.out.println(name.isEmpty()); } }Answer
true
The empty string has length 0, and isEmpty returns true.
-
What does this program print?
public class Q4 { public static void main(String[] args) { String name = "Ada"; System.out.println(name.toLowerCase()); } }Answer
ada
toLowerCase returns a new string with every letter in lower case.
-
A method returns null and the test calls
result.length()without an assertion. What does the report show?Answer
An error with a NullPointerException, not a clean assertion failure
The call throws before any assertion runs, so the report shows the exception as an error.
-
What does this program print?
public class Q5 { public static void main(String[] args) { boolean even = 10 % 2 == 0; System.out.println(even); } }Answer
true
The boolean variable holds true and println prints it as the word true.
-
Which assertion says what the test expects most clearly?
Answer
assertFalse(Flags.isEven(7), "7 should be odd")
The named assertion and the message state the rule directly; the negations hide it.
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