I'm learning how to do tests in Java with mockito I so far a used to this consept:
@Test
void createAccount_Should_Return_Account() throws InstanceAlreadyExistsException {
AccountRepository ar = mock(AccountRepository.class);
when(ar.findByUsername("floatfoo")).thenReturn(Optional.empty());
AccountService as = new AccountService(ar);
assertEquals(new Account("floatfoo", "Egor"), as.createAccount("floatfoo", "Egor"));
}
and AccountService looks like this:
public Account createAccount(String username, String name) throws InstanceAlreadyExistsException{
Optional<Account> existingAccount = this.accountRepository.findByUsername(username);
if (existingAccount.isPresent()) {
throw new InstanceAlreadyExistsException("Account with this username already exist!");
} else {
Account account = new Account(username, name);
return accountRepository.save(account);
}
}
I have tried to also mock save method from repository interface - and this is do it's job. My question is - can I do it without mocking save? And in this test assertion fails because service return null ( this means that save return null ) - why is that? Thank you for your time! :]