How to test if the following method has throw the exception when the name is null?
public boolean validateName(String name) {
if (name == null) {
throw new IllegalArgumentException("Name cannot be null");
}
if (name.isBlank()) { // checks if name is entirely whitespace
return false;
}
if (!name.contains(" ")) {
return false;
}
return true;
}
I have already test all the cases for blank name, and name containing spaces, the only one that have left is the test for when the name is null, here is what i have got:
@Test
public void handlesNullTest() {
String name = null;
NameValidator validator;
assertEquals("Name cannot be null", validator.validateName(name));
}
Is above the correct way to test for throwing exception in java Junit test? thank you.