Unit Testing
Standard validation of individual segments of functionality exposed from a class.
It is the first type of testing that can be run against code and should be run before code is committed to source control.
Stateless methods
This is the ideal type of code to validate using unit tests, if your code can be made stateless it should be.
Stateless means that code doesn’t rely on external factors like the environment.
public class ObjectHandler {
@Inject
private Service service;
private final Logger logger = LoggerFactory.getLogger(getClass());
private Result send(Object context) {
String idString = context.getId();
Result result;
// some processing occurs here updating the result object
// if this code was inline, this method would not be stateless because the result relies on the state of `Service`
// Data data = service.fetchData();
// result = context + data;
if (context) {
logger.info("processing complete for {}", idString);
return result;
}
else {
logger.info("no update required for {}", idString);
return null;
}
}
}
Stateless testing
A minimum of two tests would be required for this code, additional tests covering // some processing occurs here updating the result object
would also be needed.
public class ObjectHandlerTest {
@Inject
ObjectHandler objectHandler;
@Test
private void sendTest() {
Object context = // setup test scenario here
Result result = objectHandler.send(context);
// complete relevant assertions to verify functionality
assertIsNotNull(result);
...
}
@Test
private void sendReturnsNullTest() {
Object context = // setup test scenario here
Result result = objectHandler.send(context);
// complete relevant assertions to verify functionality
assertIsNull(result);
}
}