0

I am getting InvalidUseOfMatchersException while running the test case given below

import org.mockito.junit.MockitoJunitRunner;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.*;

@RunWith(MockitoJunitRunner.class)
public class APITest{

private RestTemplate restTemplate;

private HttpHeaders httpHeaders;

private APIService apiService;

private String url = "http://sample.com";

private String APIRequestJson = "{ \"text\":\"Greetings\" }"

private String APIResponse;

@Before
public void setup(){
    restTemplate = mock(RestTemplate.class);
    httpHeaders = mock(HttpHeaders.class);
    apiService = new APIService(restTemplate,httpHeaders);
    APIResponse = "{ \"result\":\"ok\" }"
}

@Test
public void validate_msg_bad_request() {
    ResponseEntity<?> responseEntity = new ResponseEntity<>(APIResponse, HttpStatus.BAD_REQUEST);

    when(restTemplate.exchange(
       anyString(), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))
    ).thenReturn((ResponseEntity<String>) responseEntity);

    msgResponse = apiService.validateMsg(APIRequestJson, url);

    Assert.assertequals("400",msgResponse.getStatusCode());
}

}

If I execute the test case, I am getting the exception below

Method threw 'org.mockito.exceptions.misusing.InvalidaUseOfMatchersException' exception.Cannot evaluate org.springframework.web.client.RestTemplate$MockitoMock$935390488.toString()

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
ResponseEntity cannot be returned by toString()
toString() should return String

Could you please let me know what is the problem here?

Hammy1985
  • 50
  • 8
LearnToCode
  • 169
  • 1
  • 5
  • 19
  • Does it happen in debug mode in your IDE or under normal run? – Lesiak Aug 16 '23 at 11:40
  • Debug mode gives Method threw 'org.mockito.exceptions.misusing.InvalidaUseOfMatchersException' exception.Cannot evaluate org.springframework.web.client.RestTemplate$MockitoMock$935390488.toString() – LearnToCode Aug 16 '23 at 11:55
  • Normal Run gives the error org.mockito.exceptions.misusing.WrongTypeOfReturnValue: ResponseEntity cannot be returned by toString() toString() should return String – LearnToCode Aug 16 '23 at 11:55
  • Stop using JUnit 4 (`@RunWith`); migrate to JUnit 5 (`@ExtendWith`) – knittl Aug 28 '23 at 17:52
  • Something else is wrong in your setup; I cannot reproduce the issue (Spring Boot 2.7.15 with JUnit 4). Please [edit] your question to include a _complete_ [mre]; VTC for now due to lack of reproducability – knittl Aug 28 '23 at 18:02

0 Answers0