Jeff Langr recently put out a new book Pragmatic Unit Testing in Java 8 with JUnit which I highly recommend. I’ve recently come back to Java (mostly through teaching XP courses) and wanted a refresher on some unit testing best practices. Jeff’s book didn’t disappoint.
Here are some take aways and language for for me from this great gook.
AAA – Arrange – Act – Assert
Exposing Private Data Versus Exposing Private Behavior
Try not to test private methods/data too much.
Occasionally is OK. But if you are constantly exposing deep, gobs of interesting behavior it’s usually a violations of the SRP (Single Responsibility Rule) which states that classes should be small and single-purpose
Your best bet is to extract the interesting private behavior and move to to another class where it can be public behavior.
What to test?
Flex your Right-BICEP.
Right – are the results right?
B – Boundary conditions
I – Inverse Relationships
C – Cross check results with other means
E – Error conditions
P – Performance
Remember Boundary Conditions with CORRECT
Conformance – Does the value conform to the expected format (i.e. email)
Ordering – Is the set of values ordered or unordered as appropriate
Range – Are values within acceptable min/max range.
Reference – Does the code reference anything external not under direct control of code itself
Existence – Does the value exist (is it non-null, nonzero, present in a set, so on).
Cardinality – Are there exactly enough values (0 values, 1 value, 10 values etc, off by one)
Time – Is everything happening in order? At the right time? In time?
Anyways. This is a great book and one you should definitely checkout if you are into unit testing in Java.