Tests exist to assert that the exercised code behaved as expected. Writing good assertions is therefore key to a good test. An extreme example of a test with bad assertions is one with no assertions. This seems strange, but believe it or not, it happens—not because we do not know what we are doing, but because writing a good assertion can be tricky. In cases where observing the outcome of behavior is not easily achievable, I suggest refactoring the class or method under test to increase its observability.
Assertions should be as strong as possible. You want your tests to fully validate the behavior and break if there is any slight change in the output. Imagine that a method calculateFinalPrice()
in a ShoppingCart
class changes two properties: finalPrice
and the taxPaid
. If your tests only ensure the value of the finalPrice
property, a bug may happen in the way taxPaid
is set, and your tests will not notice it. Make sure you are asserting everything that needs to be asserted.
Leave a Reply