test: add unit tests for multithreading scenarios
This commit is contained in:
@@ -1,4 +1,56 @@
|
||||
package banking;
|
||||
|
||||
import dev.banking.model.BankAccount;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class TestB {
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentDepositWithdraw() throws Exception {
|
||||
|
||||
BankAccount account =
|
||||
new BankAccount(1, 1_000_000);
|
||||
|
||||
ExecutorService executor =
|
||||
Executors.newFixedThreadPool(100);
|
||||
|
||||
CountDownLatch latch =
|
||||
new CountDownLatch(100);
|
||||
|
||||
for (int i = 0; i < 50; i++) {
|
||||
|
||||
executor.submit(() -> {
|
||||
|
||||
for (int j = 0; j < 10000; j++) {
|
||||
account.deposit(1);
|
||||
}
|
||||
|
||||
latch.countDown();
|
||||
});
|
||||
|
||||
executor.submit(() -> {
|
||||
|
||||
for (int j = 0; j < 10000; j++) {
|
||||
account.withdraw(1);
|
||||
}
|
||||
|
||||
latch.countDown();
|
||||
});
|
||||
}
|
||||
|
||||
latch.await();
|
||||
|
||||
executor.shutdown();
|
||||
|
||||
assertEquals(
|
||||
1_000_000,
|
||||
account.getBalance()
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user