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

标签 java unit-testing junit tdd hamcrest

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

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/

相关文章:

android - Robolectric 单元测试 build.os 版本返回不正确?

java - JUnit 在测试中捕获异常

Java Swing OSX 窗口菜单复选标记

java - 无法保留具有共享 ID 的实体

java - GWT 中的 Google Drive 身份验证

c# - 如何等待异步命令进行单元测试?

c# - 对运行时命中应用程序的 API 调用进行单元测试的最佳方法

maven - 如何对 PlayN 项目进行单元测试?

database - 在测试 API 时编写用于验证数据库条目的测试代码

java - 如何使用eclipse在java中的类中添加默认字符串