How can I verify repository invocation?

Viewed 57

Say I have a repository interface looks like this,

@Repository
interface MyRepository {

    Optional<My> findByOtherId(long otherId);

    default Optional<My> findByOther(Other other) {
        return findByOtherId(other.getId());
    }
}

I'm trying to invoke findByOther and verifies that the call invokes findByOtherId method.

@DataJpaTest
class MyRepositoryTest {

    @Test
    void test() {
        Other other = new Other(0L);
        repository.findByOther(other);
        verify(other, times(1)).getId(); // verified
        verify(repository, times(1)).findByOtherId(other.getId()); // called, yet not verified!
    }


    @SpyBean
    private MyRepository repository;
}

When I debug, the findByOtherId method is called. But mockito complains it doesn't.

How can I do this?

1 Answers

As far as I understand you are trying to mock a methodCall that is done from inside the SpyBean. You are essentially trying to verify a private method call (even though findByOtherId can have the public modifier). That is why Mockito complains. As far as I know, mockito creates proxys around its spies. Similar to how spring proxies its beans. I don´t think what you are trying to achieve is solved that way.

For a solution, I would suggest looking into PowerMock. There might be a solution in there. https://www.baeldung.com/powermock-private-method

verifyPrivate(mock).invoke("saveIntoDatabase", ArgumentMatchers.anyString());
Related