Last active
July 1, 2020 16:45
-
-
Save mcculley/5a13ac0db0b73dc92b8e8f52767a9376 to your computer and use it in GitHub Desktop.
Class with embedded tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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