The thing is 'when' from io.codearte package is compliant with org.mockito.Mockito.any() on compilation level, but fails during runtime with that exact same error message.
Basically You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
For example:
PowerMockito.mockStatic(TestClass.class);
when(TestClass.getString()).thenReturn("HelloWorld!");
Note: you have to add @PrepareForTest({ TestClass.class })
to your unit test class.
When I got this exception, I was using @InjectMocks on the class that I needed to have the @Mock objects injected into (via constructor injection).
AFter much searching, I finally stumbled across this article:
https://mkyong.com/spring-boot/mockito-when-requires-an-argument-which-has-to-be-a-method-call-on-a-mock/
The key part to take away from it is (from the article):
When Mockito see this @InjectMocks, it doesn’t mock it, it just
creates a normal instance, so the when() will be failed.
So this make this exception message I was getting
when() requires an argument which has to be 'a method call on a mock'.
make sense now; you aren't using when on an actual mock but an actual instance.
The link also provides the solution to the problem:
To solve it, annotate @Spy to mock it partially.
On top of @InjectMocks, put @Spy.
As a side note, if you try to make it a Mock by putting @Mock on top of @InjectMocks, you will get exception:
org.mockito.exceptions.base.MockitoException: This combination of
annotations is not permitted on a single field: @Mock and @InjectMocks
Using @Spy on top of @InjectMocks solved the problem for me.
I faced same issue and it was because the mocked object is defined as @Bean
and the overriden @Bean
in the test was not working because of a missing spring property value
@Bean
@Primary
public JwtTokenUtil jwtTokenUtil() {
return Mockito.mock(JwtTokenUtil.class);
@Autowired
private JwtTokenUtil jwtTokenUtil;
when(jwtTokenUtil.validateToken(jwtToken)).thenReturn(true);
spring.main.allow-bean-definition-overriding=true
in application-test.properties
if anything above answers your case, then check that you did missed the @Test
annotation for your test method.
@Test
public void my_test_method(){
just quoting, as this was my case. just missed the annotation.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.