gpt4 book ai didi

java - 为什么这个测试能通过?

转载 作者:行者123 更新时间:2023-12-02 01:13:30 25 4
gpt4 key购买 nike

我需要您的帮助来理解如下所示的单元测试类中的单元(方法)行为。

public void updateAccount(Account account) {
if (!accountExists(account.getAccountNo())) {
throw new AccountNotFoundException();
}
accounts.put(account.getAccountNo(), account);
}

上面的方法告诉我,如果找不到帐户就会抛出异常

但是,下面显示的第二个测试 (updateNotExistedAccount) 方法表明,预计上面的方法 (updateAccount) 应抛出异常以通过测试。但是,newAccount 已在 createNewAccount 中初始化/创建,因此它已经存在。因此,我假设 updateNotExistedAccount 将无法通过测试(因为 updateAccount 在这种情况下不会抛出异常),但是 updateNotExistedAccount 通过了。

    public class InMemoryAccountDaoTests {
private static final String NEW_ACCOUNT_NO = "998";
private Account newAccount;
private InMemoryAccountDao accountDao;

@Before
public void init() {

newAccount = new Account(NEW_ACCOUNT_NO, 200);
accountDao = new InMemoryAccountDao();
}

@Test
public void createNewAccount() {
accountDao.createAccount(newAccount);
assertEquals(accountDao.findAccount(NEW_ACCOUNT_NO), newAccount); }



@Test(expected = AccountNotFoundException.class)
public void updateNotExistedAccount() { accountDao.updateAccount(newAccount);
}

如果我假设 updateNotExistedAccount 将无法通过测试,这是错误的吗?

最佳答案

似乎数据从一个测试保留到另一个测试。每次测试后尝试清理数据。

@After
public void clean(){
// this method will be run after each single @Test method
// you can use this to clean all resoruces after a test. in your case for example
accountDao.deleteById(newAccount.getId());
}

为了让您的测试完成并测试更新,我会执行以下操作:

@Test
public void updateExistingAccount() {
accountDao.createAccount(newAccount);
dbAccount = accountDao.findAccount(newAccount.getId);
dbAccount.setName("");
dbAccount.setSurname("");
// etc...
accountDao.updateAccount(dbAccount);
dbAccountUpdated = accountDao.findAccount(newAccount.getId);
assertEquals(accountDao.findAccount(dbAccountUpdated.getId()), dbAccount);
}

更新
还要考虑 @Before@After 分别在每个测试之前和之后运行。@BeforeClass@AfterClass 分别在所有测试之前和之后。

通过使用这 4 种方法,您始终可以使用所需的数据集开始测试,并在测试后按原样清理所有内容。
请参见: Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

关于java - 为什么这个测试能通过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59009422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com