Introduction to Testing in Java
Maria Milusheva
Senior Software Engineer
Two key concepts:
Unit - the smallest testable part of an application, such as a method
Unit testing - A test that focuses on verifying the correctness of a single "unit" of code in isolation from other parts of the application
Notes:
Unit testing is about small pieces of logic, not the big picture
Other types of testing focus on the big picture (e.g. integration)
JUnit gets its name because its primary use case is unit testing
assertTrue()
checks that a statement is true: List<String> list = new ArrayList<>();
assertTrue(list.isEmpty()); // No error
assertFalse()
checks the opposite:List<String> list = new ArrayList<>();
list.add("A");
assertFalse(list.isEmpty()); // No error
null
variables can lead to NullPointerException
!
Assertions that check a variable is or isn't null
- assertNull()
and assertNotNull()
Common use case: checking a value retrieved from somewhere is not null
Map<String, Integer> catalogue = new HashMap<>();
catalogue.put("item1", 10);
// No errors
assertNotNull(catalogue.get("item1"));
assertNull(catalogue.get("item2"));
Suppose we want to verify an ArrayIndexOutOfBoundsException
is thrown:
public String getIndex(String[] array, int index) {
return array[index];
}
JUnit provides multiple ways to do this!
JUnit provides assertThrows()
, but it uses advanced Java syntax (lambda expressions)
Can use assertInstanceOf()
like this:
try {
getIndex(4);
} catch (Exception e) {
// Pass the expected class of the exception and the exception itself
assertInstanceOf(ArrayIndexOutOfBoundsException.class, e);
}
A typical project contains hundreds of unit tests
They should be lightweight and simple to understand
They should have informative names so that we can see at first glance what went wrong if one of them fails
For example: methodUnderTest_expectedBehavior_conditions()
Introduction to Testing in Java