spring-boot: Unable to create working mock() for Spring Data Repository
I have a regression upgrading to Spring Boot 2.3.0.RELEASE.
According to https://github.com/spring-projects/spring-boot/issues/7033
I try creating a Mock manually like
@Primary
@Bean
MyRepository testBean(MyRepository real){
var mock = mock(MyRepository.class,
AdditionalAnswers.delegatesTo(real));
when(mock.count()).thenReturn(100L);
return mock;
}
Calling verify() on that mock fails with Argument passed to verify() is of type $Proxy82 and is not a mock!
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Reactions: 1
- Comments: 18 (10 by maintainers)
Thanks, @NicklasWallgren.
@odrotbohm was correct above and it’s happening because you are not configuring the exceptions in the way that is required when
AdditionalAnswers.delegatesTo(real)is used. Taken from its javadoc:This means that your
saveUsingSpy()method should be modified to look like this:With this change in place, all 4 tests in your sample pass for me.
@odrotbohm @jhoeller using ObjectProvider did the trick!
Could make it work in a single file, can’t believe spring recognizes the repository.
@MockBeanand@SpyBeanonly force the context to be recreated if you do not have a consistent set of mocks and spies across all of your tests. If you have the same@MockBeanand@SpyBeanconfiguration in every test class, the tests will all share a single application context.If you have any further questions, please follow up on Stack Overflow or Gitter. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.
Just a quick note: the stack trace suggests that the mock is not used as it shows
SimpleJpaRepositorydoing its thing trying to persist anullhanded to….save(…).@NicklasWallgren Thanks for letting us know. It’s hard to tell what the cause is from the stacktrace above, but on the face of it, I don’t think it’s the same problem as this issue was tracking. It could be another variant of #7033 but I’m not sure that it is. I think the best option at this point is a new issue for now at least. If you’d like us to spend some more time investigating, can you please open one and provide a minimal sample that reproduces the stacktrace you have shared above?
I tried the
ObjectProvidertrick above, and it worked great, but I have encountered another issue.It seems like I’m unable to mock
CrudRepository::save.The following mock results in an exception.
Mockito.when(repository.getIfAvailable().save(any(MyEntity.class))).then(returnsFirstArg());.