Skip to content

Instantly share code, notes, and snippets.

@mcculley
Last active July 1, 2020 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcculley/5a13ac0db0b73dc92b8e8f52767a9376 to your computer and use it in GitHub Desktop.
Save mcculley/5a13ac0db0b73dc92b8e8f52767a9376 to your computer and use it in GitHub Desktop.
Class with embedded tests
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class Account {
public static class InsufficientFundsException extends Exception {
}
private int balance;
public synchronized void transferTo(final int amount, final Account destination) throws InsufficientFundsException {
synchronized (destination) {
withdraw(amount);
destination.deposit(amount);
}
}
public synchronized void withdraw(final int amount) throws InsufficientFundsException {
if (sufficientFunds(amount)) {
balance -= amount;
} else {
throw new InsufficientFundsException();
}
}
public synchronized void deposit(final int amount) {
balance += amount;
}
public synchronized int balance() {
return balance;
}
private boolean sufficientFunds(final int amount) {
return balance >= amount;
}
@Test
private static void testTransactions() throws Account.InsufficientFundsException {
Account account = new Account();
account.deposit(100);
assertEquals(100, account.balance());
account.withdraw(60);
assertEquals(40, account.balance());
}
@Test
private static void testFailedTransaction() {
Account account = new Account();
account.deposit(100);
assertEquals(100, account.balance());
assertThrows(Account.InsufficientFundsException.class, () -> account.withdraw(101));
}
@Test
private static void testTransfer() throws Account.InsufficientFundsException {
Account account1 = new Account();
Account account2 = new Account();
account1.deposit(100);
account1.transferTo(100, account2);
assertEquals(100, account2.balance());
assertEquals(0, account1.balance());
}
@Test
private static void testFailedTransfer() {
Account account1 = new Account();
Account account2 = new Account();
account1.deposit(100);
assertThrows(Account.InsufficientFundsException.class, () -> account1.transferTo(101, account2));
assertEquals(0, account2.balance());
assertEquals(100, account1.balance());
}
static {
TestUtilities.runTests();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment