Write trustworthy unit tests

A trustworthy unit test is a test you can trust. It should fail when the code is broken, and succeed when – and only when – the code behaves like expected. If these two conditions are not met then the unit test is not trustworthy.

Example

The following test is not trustworthy. According the test name, we want to validate that the balance updates accordingly after a deposit using the deposit() method. One thing we notice right away is that the assertion we used is not enough: If for some reason the deposit() we will never know since the unit test will be still successful, which is not good.

@Test
void deposit_Should_Update_Balance_when_Non_Null_Amount_Provided(){
// arrange
double AMOUNT = 100.00;
BankAccount bankAccount = new BankAccount();

// act
bankAccount.deposit(AMOUNT);

// assert
assertTrue( bankAccount.getBalance() > 0 ) ;
}

Improved example

To make the unit test trustworthy, we need to define an expected balance and use a more accurate assertion:

@Test
void deposit_Should_Update_Balance_when_Non_Null_Amount_Provided(){
// arrange
double AMOUNT = 100.00;
double EXPECTED_BALANCE = 100.00;
BankAccount bankAccount = new BankAccount();

// act
bankAccount.deposit(AMOUNT);

// assert
assertEquals(EXPECTED_BALANCE, bankAccount.getBalance() );
}

note

In java, it’s a bad practice to use the primitive type double for real world monetary values. In production code, use more appropriate types like BigDecimal.

Leave a Reply

Your email address will not be published. Required fields are marked *