Bhushan Uniyal
Bhushan Uniyal

Reputation: 5703

Unit test case MockRestServiceServer expected url is not working with RestTemplate

I have test a url class which validate url

class ValidateUrl {
    public Integer validateUrl(String url, int timeOut) throws Exception {
        String url;
        private RestTemplate restTemplate = new RestTemplate();
        try {
            ((SimpleClientHttpRequestFactory)restTemplate.getRequestFactory()).setConnectTimeout(1000 * timeOut);
            ResultClass result = restTemplate.postForObject(url, null, ResultClass.class);
            if(result!= null) {
                return result.getErrorCode();
            }

        } catch (Exception e) {
            log.error("Error"+ e);
        }
        return -1;

    }
}

i have create a test case of test class ValidateUrlTest where i am validating the url

@Autowire
private ValidateUrl validateUrlInstance

private String url = "https://testingurl.com";
private String result = "{\"result\" : \"-1\"}";

@Test
public void validateUrlTest() throws Exception{
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    RestTemplate template = new RestTemplate(factory);
    MockRestServiceServer server = MockRestServiceServer.createServer(template);
    server.expect(requestTo(url))
            .andRespond(given());
    int i= validateUrlInstance.validateUrl(url, 2);
    server.verify();

}

but getting java.lang.AssertionError: Further request(s) expected [testng] 0 out of 1 were executed

Upvotes: 0

Views: 3156

Answers (1)

Matt
Matt

Reputation: 3662

The instance of RestTemplate you are mocking is not the one used in ValidateUrl class.

You should inject it instead of intanciating it straight in the method.

public class ValidateUrl {

    private RestTemplate restTemplate;

    @Autowired
    public ValidateUrl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public Integer validateUrl(String url, int timeOut) throws Exception {
     ...
    }
}

Upvotes: 1

Related Questions