Home > Software design >  Spring Data JPA and Mockito - why save() return null in test?
Spring Data JPA and Mockito - why save() return null in test?

Time:08-16

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! :]

CodePudding user response:

Well, if you are using Entity at the point of creating new Account() it generates new id which would mean they are not equal.

also read about @InjectMocks annotation which would help with mocking service and repo layers.

you can try something like:

Account newAccount = new Account("test1", "Egor");

AccountRepository ar  = mock(AccountRepository.class);
AccountService as = new AccountService(ar);

when(ar.save(any())).thenReturn(newAccount);
Optional<Account> acc = as.createAccount(newAccount);
assertTrue(acc.isPresent());
assertEquals(acc, newAccount);
  • Related