【发布时间】:2021-03-13 20:11:08
【问题描述】:
我有一个 junit5 的测试类。 我的生产程序使用 MySQL 数据库。带有一些初始数据。 每次测试函数调用后如何重置我的数据库? 我应该使用弹簧吗?
这是我的测试类:
类 ATMTest {
private ATM atm;
@BeforeEach
void setUp() {
//TODO: initialize the atm here
atm = new ATMClass();
}
@Test
void givenAccountNumberThatDoesNotExist_whenWithdraw_thenShouldThrowException() {
Assertions.assertThrows(AccountNotFoundException.class,
() -> atm.withdraw("14141414141", new BigDecimal("120.0")));
}
@Test
void givenValidAccountNumber_whenWithdrawAmountLargerThanTheAccountBalance_thenShouldThrowException() {
Assertions.assertThrows(InsufficientFundsException.class,
() -> atm.withdraw("123456789", new BigDecimal("20000.0")));
}
@Disabled
@Test
void whenWithdrawAmountLargerThanWhatInMachine_thenShouldThrowException() {
atm.withdraw("123456789", new BigDecimal("1000.0"));
atm.withdraw("111111111", new BigDecimal("1000.0"));
Assertions.assertThrows(NotEnoughMoneyInATMException.class,
() -> atm.withdraw("444444444", new BigDecimal("500.0")));
}
@Test
void whenWithdraw_thenSumOfReceivedBanknotesShouldEqualRequestedAmount() {
BigDecimal requestedAmount = new BigDecimal(700);
List<Banknote> receivedBanknotes = atm.withdraw("111111111", requestedAmount);
BigDecimal sumOfAllBanknotes = receivedBanknotes.stream().map(Banknote::getValue).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
Assertions.assertEquals(sumOfAllBanknotes.compareTo(requestedAmount), 0);
}
@Test
void givenAllFundsInAccountAreWithdrwan_whenWithdraw_shouldThrowException() {
atm.withdraw("222222222", new BigDecimal("500"));
atm.withdraw("222222222", new BigDecimal("500"));
Assertions.assertThrows(InsufficientFundsException.class,
() -> atm.withdraw("222222222", new BigDecimal("500")));
}
}
每个测试函数都需要使用数据的初始状态。
【问题讨论】:
-
为什么要使用实时数据库进行单元测试?
-
使用装有数据库的容器。
-
您可以使用像 h2 这样的内存数据库,或者使用带有 AfterEach 或 After 注释的 tearDown() 在其中您将添加逻辑以恢复测试运行期间发生的任何插入/更新等。
-
您可能想了解 schema migration 工具,例如 Flyway、Liquibase 等。
-
您可以每次设置初始数据以确保一致性。
标签: java sql spring unit-testing junit5