如何验证存储库调用?

发布于 2025-01-22 10:10:17 字数 868 浏览 0 评论 0原文

假设我有一个像这样的存储库接口,

@Repository
interface MyRepository {

    Optional<My> findByOtherId(long otherId);

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

我正在尝试调用Findbyother,并验证调用调用是否调用Findbyotherid方法。

@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;
}

当我调试时,调用Findbyotherid方法。但是Mockito抱怨​​并非如此。

我该怎么做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怕倦 2025-01-29 10:10:17

据我了解,您正在尝试嘲笑从Spybean内部完成的方法。您本质上是在尝试验证一个私人方法调用(即使Findbyotherid可以具有public修改器)。这就是为什么Mockito抱怨​​的原因。据我所知,Mockito在其间谍周围创建了代理人。类似于春季代理豆子的方式。我不认为您要实现的目标是这样解决的。

对于解决方案,我建议您研究PowerMock。那里可能有一个解决方案。 https://wwwww.baeldung.com/powermock-private-private-method-method

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

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());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文