A Classic-Style Assertion: assertTrue

This lesson will explain the use and importance of using assertTrue in writing Unit tests.

We'll cover the following

The most basic Classic-Style Assertion is assertTrue:

org.junit.Assert.assertTrue(someBooleanExpression); 

Since assertions are so pervasive in JUnit tests, most programmers use a static import to reduce the clutter:

import static org.junit.Assert.*; 

An assertTrue ensures that a value is true, otherwise it gives a false. A couple of examples:

@Test
public void hasPositiveBalance() {
   account.deposit(50);
   assertTrue(account.hasPositiveBalance());
}

If the parameter in assertTrue evaluates as true, then the above test will pass.

@Test
public void depositIncreasesBalance() {
   int initialBalance = account.getBalance();
   account.deposit(100);
   assertTrue(account.getBalance() > initialBalance);
}

The above test (depositIncreasesBalance) is testing whether the balance in an account is greater than the initial balance after a deposit of 100 is added. The assertTrue assertion makes sure that the condition is true.

@Before Account instance

The previous examples depend on the existence of an initialized Account instance. We can create an Account in an @Before method and store a reference as a field in the test class:

private Account account; 
@Before
public void createAccount() {
   account = new Account("an account name");
}

We have been provided with an Account class in this example. Run the tests below to check if they pass.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy