tests working in mockito 4.x are not working with mockito 5.x getting error
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(any());
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.
sample code :
@ActiveProfiles("test")
@ExtendWith(SpringExtension.class)
@WebMvcTest(SampleApiController.class)
@Slf4j
https://github.com/import({MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class})
public class GetFailedTest {
@MockBean
MockClass Mockobj;
JsonFileReader reader = new JsonFileReader();
@Autowired
MockMvc mockMvc;
@BeforeAll
static void setUpBeforeClass() throws Exception {
System.setProperty("junit", "true");
}
@Test
void testSampleFail() throws Exception {
log.info("testSampleFail");
String url = "xxxxx";
when(Mockobj.getMethod(anyString(), org.mockito.Mockito.any(StringBuilder.class)))
.then(new Answer() {
@Override
public Integer answer(InvocationOnMock invocation) throws Throwable {
StringBuilder sbd = invocation.getArgument(1);
sbd.append(reader.getJsonStringFromFile(Constants.sample));
throw new RuntimeException("Runtime exception");
}
});
MvcResult result = this.mockMvc.perform(get(url)).andExpect(status().is5xxServerError()).andReturn();
log.info(result.getResponse().getContentAsString());
}
}
Comment From: wilkinsona
You need to correct your usage of Mockito. I would expect the complete error and stack trace to help to pinpoint what needs to be changed. If it does not, and you require some further help, please follow up on Stack Overflow. The Spring Boot issue tracker is not the right place to seek help with a Mockito 4.0 to 5.0 migration.