0

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

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如果我假设考试会失败,那是错的吗?

4

2 回答 2

1

似乎数据从一个测试持续到另一个测试。尝试在每次测试后清理数据。

@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 种方法,您可以始终使用所需的数据集开始测试,并在测试后按原样清理所有内容。
请参阅: @Before、@BeforeClass、@BeforeEach 和 @BeforeAll 之间的区别

于 2019-11-23T16:21:16.800 回答
1

要正确检查需要查看您的newAccount代码以及您正在模拟的内容。

  • 检查您的@Before方法,因为它将在每个@Test
  • 运行套件时检查是否先运行哪个测试
于 2019-11-23T16:21:51.760 回答