每次测试单元功能后如何重置数据库?

时间:2021-03-13 20:11:08

标签: java sql spring unit-testing junit5

我有一个带有 junit5 的测试类。 我的生产程序使用 MySQL 数据库。有一些初始数据。 每次测试函数调用后如何重置我的数据库? 我应该使用 spring 吗?

这是我的测试课:

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

}

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

2 个答案:

答案 0 :(得分:0)

单元测试的目标是隔离程序的每个部分,并表明各个部分是正确的。 因此,您不必使用实时数据库,而是提供一些模拟从数据库返回值的 mocksstubs(例如使用 Mockito) .

否则你所做的就是所谓的集成测试。

回答问题,用@BeforeEach 创建基础类。在那里您可以实现截断所有表。这样,在每个@Test 方法之前就可以设置所有需要的数据。

答案 1 :(得分:0)

如果您想进行集成测试(而不是单元测试),并且希望将数据库重置为已知状态,我建议您使用 3rd 方库,例如 DbUnit。 (http://dbunit.sourceforge.net)

如果项目很小并且“设置”并不难,您也可以自己动手。