1

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?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184

1 Answers1

0

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());
HariHaravelan
  • 1,041
  • 1
  • 10
  • 19
GJohannes
  • 1,408
  • 1
  • 8
  • 14
  • 1
    Correction in order to not confuse the OP or anyone else reading your answer: We are not talking about "private" method calls here, but about **self-invocation** instead. The latter cannot be intercepted in proxy-based Spring AOP, only in native AspectJ which does not use proxies. Some background info about how this works internally is [here](https://stackoverflow.com/a/56616248/1082681). A Spring workaround using `@Autowired` is also briefly mentioned there. Please keep your hands off PowerMock, if you can. Using it promotes bad code design instead of better testability. – kriegaex Apr 19 '22 at 05:37