When writing unit tests for existing source code, it was necessary to perform tests to verify whether they were null as the title suggests. I have briefly summarized what I learned in the process.
The tool and version I'm using is JUnit 4 (.12) and Hamcrest is 1.3.
This time, I will write it on the assumption that I will write a test in the Prefix Adder of ↓.
PrefixAdder.java
public class PrefixAdder {
public static String execute(String target, String prefix) {
if (Objects.isNull(target)) {
return null;
}
return prefix + target;
}
}
At first, I intuitively wrote the following as usual, but this way of writing results in a compilation error at a level that warns the IDE.
PrefixAdderTest.java
public class PrefixAdderTest {
@Before
public void setUp() {
}
@Test
public void returnNullWhenTargetIsNull() {
String result = PrefixAdder.execute(null, "prefix");
//↓ Compile error
assertThat(result, is(null));
}
}
So how to write it is to use the nullValue method of Hamcrest's IsNull class.
PrefixAdderTest.java
public class PrefixAdderTest {
@Before
public void setUp() {
}
@Test
public void returnNullWhenTargetIsNull() {
String result = PrefixAdder.execute(null, "prefix");
assertThat(result, nullValue());
}
}
Now you can test for null. If you want to test that it is not null, you can also use the notNullValue method of the IsNull class.
If you want to write a test that verifies whether a value is null in JUnit, use the nullValue method of Hamcrest's IsNull class. If you use the is method of the Is class in the usual way, a compile error will occur.
It's easy, but I hope this article has helped you a little.
Hamcrest Tutorial Hamcrest GitHub IsNull class
Recommended Posts