GWFreak01
GWFreak01

Reputation: 11

Unable to mock Micronaut repository in unit test

I'm still fairly new to Micronaut.

I've been struggling to figure out why I keep running into this testing error:

AuthenticationHelperTest > testCreateAccount() FAILED
    java.lang.NullPointerException: accountRepository.save(accountModel) must not be null

I can manually test my endpoint via POSTMAN and it creates an account perfectly fine in the database but fails on a test case.

import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import java.time.LocalDateTime
import java.time.ZoneId

class AuthenticationHelperTest {
    private val accountRepository = Mockito.mock(AccountRepository::class.java)
    @Test
    fun testCreateAccount() {
        val account = Account(
            ...
        )
        Mockito.`when`(accountRepository.save(account)).thenReturn(Account(
            ...
        ))

        val sut = AuthenticationHelper(accountRepository)

        val accountDto = AccountDto(
            ...
        )

        val result = sut.createAccount(accountDto)

        Assertions.assertEquals(1, result.id)
    }
}

Thanks for any leads!

Upvotes: 1

Views: 1639

Answers (2)

Hantsy
Hantsy

Reputation: 9321

Micronaut provides a@MockBean to declare a mocked in a test.

@MicronautTest
class SomeTest {

    @Inject AccountRepository bean;

    @Test
    public void testSomething(){}

    @MockBean(AccountRepository.class) 
    AccountRepository mockedAccountRepository(){
       return mock(AccountRepository.class);
    }
}

There is an complete example using @MockedBean. But from my experience, the Mockbean only works on an interface.

Upvotes: 1

Cedric
Cedric

Reputation: 124

You should try to run your test with MockitoExtension

@ExtendWith(MockitoExtension.class)
class AuthenticationHelperTest

And use @Mock annotation for accountRepository

@Mock
private val accountRepository;

Upvotes: -1

Related Questions