![](/img/trans.png)
[英]Junit : Runlistener overriden method (testFinished) not called when running a Parameterized test
[英]Junit Test Pass even when the method called inside may fail
我正在創建一個 Junit 單元測試來檢查服務中調用 Service 輔助方法的 createAccount 方法。 請在下面找到它。
客服 class
public class AccountServiceImpl {
@Autowired
AccountHelper accountHelper;
@Override
public Account createAccount(Account account) throws CustomerNotFoundException {
accountHelper.checkAccountTypeForCustomer(account);
return accountRepository.save(account);
}
}
助手Class:
public void checkAccountTypeForCustomer(Account acc) throws CustomerNotFoundException {
Boolean customerExists = customerRepository.existsById(acc.getCustomerId());
if(!customerExists) {
throw new CustomerNotFoundException("604", Message.CUSTOMER_NOT_FOUND);
}
}
賬戶服務測試 class
@ExtendWith(MockitoExtension.class) 公共 class AccountServiceTest {
@Mock
private AccountRepository accountRepository;
@Mock
private CustomerRepository customerRepository;
@Mock
private AccountHelper accountHelper;
@InjectMocks
private AccountService testService;
@Test
void testCreateAccount() throws CustomerNotFoundException {
Account account = Account.builder().
accountType(AccountType.SAVINGS).
openingBalance(BigDecimal.valueOf(3000)).
ifsc("IFSC1").
customerId(1).
build();
testService.createAccount(account);
} }
盡管客戶不在數據庫中,但上面的測試通過了。 測試不完整。 但還是聲明:testService.createAccount(account); 根據我的理解必須失敗。
如果我錯了,請糾正我。 我對 Junit 比較陌生。
但是,如果我將 checkAccountTypeForCustomer() 的實現放在服務方法中而不是幫助程序中,測試用例將按預期失敗。
原因是您的測試中模擬了accountHelper
,這意味着調用accountHelper.checkAccountTypeForCustomer(account)
不會執行您的業務代碼。
在這種情況下,我建議您使用 Spring mocking,並指定您的存儲庫的預期行為方式。 它看起來像這樣:
@ExtendWith(SpringExtension.class)
class AccountServiceTest {
@MockBean
private CustomerRepository repository;
@Autowired
private AccountService testService;
@Test
void testCreateAccount() throws CustomerNotFoundException {
Mockito.when(repository.existsById(anyInt())).thenReturn(false);
...
CustomerNotFoundException thrown = Assertions.assertThrows(CustomerNotFoundException.class, () -> testService.createAccount(account));
Assertions.assertEquals("the exception message", thrown.getMessage());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.