unit-testing Getting started with unit-testing Simple Java+JUnit Test


JUnit is the leading testing framework used for testing Java code.

The class under test models a simple bank account, that charges a penalty when you go overdrawn.

public class BankAccount {
    private int balance;

    public BankAccount(int i){
        balance = i;

    public BankAccount(){
        balance = 0;

    public int getBalance(){
        return balance;

    public void deposit(int i){
        balance += i;

    public void withdraw(int i){
        balance -= i;
        if (balance < 0){
            balance -= 10; // penalty if overdrawn

This test class validates the behaviour of some of the BankAccount public methods.

import org.junit.Test;
import static org.junit.Assert.*;

// Class that tests
public class BankAccountTest{

    BankAccount acc;

    @Before                        // This will run **before** EACH @Test
    public void setUptestDepositUpdatesBalance(){
        acc = new BankAccount(100);  

    @After                        // This Will run **after** EACH @Test
    public void tearDown(){
    // clean up code

    public void testDeposit(){
       // no need to instantiate a new BankAccount(), @Before does it for us



    public void testWithdrawUpdatesBalance(){    

        assertEquals(acc.getBalance(),70); // pass

    public void testWithdrawAppliesPenaltyWhenOverdrawn(){