繁体   English   中英

每个测试单元 function 后如何重置数据库?

[英]How to reset the database after each test unit function?

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

这是我的测试 Class:

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

}

每次测试function需要使用数据的初始state。

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

否则,您正在做的事情称为集成测试。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM