Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring Data JPA and Mockito – why save() return null in test?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading