spring-projects / spring-projects/spring-framework

Mockito cannot mock AspectJ-woven `@Async` method

Open
#24,724 15 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

in: test type: bug
Dominant language
Java
Stars
60.2k
Forks
38.8k
Avg merge
5d 2h
Merged PRs (30d)
27

Description

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)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the failure with an AspectJ-woven @Async method invoked through a @SpyBean, using the reported Spring Boot, Mockito, and Spring Test versions. Inspect the generated TestClass.init_aroundBody0(File.java:79) stack-trace location and compare runs with and without the debugger. Done means the test no longer reports the misplaced matcher error without requiring a debugger.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, spring
Domain
backend, testing
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.