如何验证存储库调用?
假设我有一个像这样的存储库接口,
@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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我了解,您正在尝试嘲笑从Spybean内部完成的方法。您本质上是在尝试验证一个私人方法调用(即使Findbyotherid可以具有
public
修改器)。这就是为什么Mockito抱怨的原因。据我所知,Mockito在其间谍周围创建了代理人。类似于春季代理豆子的方式。我不认为您要实现的目标是这样解决的。对于解决方案,我建议您研究PowerMock。那里可能有一个解决方案。 https://wwwww.baeldung.com/powermock-private-private-method-method
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