spring-framework: Mockito cannot mock AspectJ-woven `@Async` method
When trying to mock an @Async method from a @SpyBean I get the following error:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced or misused argument matcher detected here:
-> at package.TestClass.init_aroundBody0(File.java:79)
-> at package.TestClass.init_aroundBody0(File.java:79)
You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))
This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use
Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.
This error only appears when I run the test without debugger attached. When I try to debug, the error doesn’t show up, and everything works fine.
When I remove the @Async, then it works also without the debugger attached.
This error started showing up after I upgraded from spring 4 to spring 5. Using spring-boot-starter-test 2.1.6.RELEASE (mockito-core:2.23.4, spring-test:5.1.8.RELEASE)
About this issue
- Original URL
- State: open
- Created 7 years ago
- Reactions: 2
- Comments: 15 (9 by maintainers)
Hello, we have this issue too. Usecase: We want to test the caching. Problem: With a @SpyBean it does not work. The same test runs with an autowired bean. If the Bean is with @SpyBean intialized the values for the cachekey becomes null. Workaround: As workaround, we could use an autowired bean in this case. But if we do so, the (collection of) tests tooks more time. We want to have only one “base” test file with all beans initialized with @SpyBean, so we can mock or not in every test case. The advantage is that no spring context will be reloaded and the tests runs faster.
Here’s a modified version of the code above that reproduces the problem without any involvement from Spring Boot. The key difference is that
@EnableAutoConfigurationhas been replaced by aTaskExecutor@Beanon theApplicationclass.The following reproduces the problem:
Note that
AsyncSpyTestsis itself not using any Spring Boot functionality butApplicationis due to its use of@EnableAutoConfiguration. The test passes when this line is commented out so it appears that there is something that Spring Boot is doing that’s causing the problem.We’ve seen a few issue like this in the past related to AOP. I’ll transfer the issue.