如何在每个测试单元函数之后重置数据库?

xwbd5t1u  于 2021-07-22  发布在  Java
关注(0)|答案(2)|浏览(215)

我有一个junit5的测试班。我的生产程序使用mysql数据库。一些初始数据。如何在每次测试函数调用后重置数据库?我应该用Spring吗?
这是我的测试课:
上课时间{

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")));
}

}
每个测试函数都需要使用数据的初始状态。

ct2axkht

ct2axkht1#

单元测试的目标是隔离程序的每个部分,并显示各个部分是正确的。因此,您所要做的不是使用live数据库,而是提供一些mock或stub(例如,使用mockito)来模拟从数据库返回的值。
否则,您所做的就是集成测试。
回答问题,用@beforeach创建基本类。在那里可以实现截断所有表。这样,在每个@test方法之前,您就可以设置所需的所有数据。

tcbh2hod

tcbh2hod2#

如果您想进行集成测试(而不是单元测试),希望将数据库重置为已知状态,我建议使用第三方库,如dbunit(http://dbunit.sourceforge.net)
如果项目很小,而且“设置”并不难,你也可以自己滚动。

相关问题