1

I created a mock class which has different methods WHen I tried to get the different response based on my scenarios. Im getting the error like

'System.TypeException: Mock object doesn't implement the supplied interface'

@isTest
global class MockHTTPResponseGenerator implements HttpCalloutMock{
    global HttpResponse response1(HttpRequest req) {}
    global HttpResponse response1(HttpRequest req) {}
}
Test.setMock(HttpCalloutMock.class, new MockHTTPResponseGenerator().response1(req));

2 Answers 2

4

As the error message suggests, your mock class hasn't implemented the interface which you have mentioned i.e. you have not implemented the respond method of HttpCalloutMock interface.

So, your mock class should be using below line

global HttpResponse response(HttpRequest req) {}

instead of

global HttpResponse response1(HttpRequest req) {}

Also, you are setting the mock incorrectly, Test.setMock takes two parameters, For the first argument, it takes HttpCalloutMock.class, and for the second argument, it takes a new instance of your interface implementation of HttpCalloutMock, which should be

Test.setMock(HttpCalloutMock.class, new MockHTTPResponseGenerator());

And if you want to have your response based on certain scenarios, then there are different ways to do that, one of them is by passing the parameters to your mock class via constructor.

global class MockHTTPResponseGenerator implements HttpCalloutMock{
    Integer statusCode;
    global MockHTTPResponseGenerator(Integer strStatusCode){
        statusCode = strStatusCode;
    }
    global HttpResponse response(HttpRequest req) {
        //based on the status code, you can respond differently
        if(statusCode==200){
            //set response
        } else if(statusCode==any other code){
            //set response
        }
        return httpresponse;
    }
}

And you can set mock by passing the status code

Test.setMock(HttpCalloutMock.class, new MockHTTPResponseGenerator(200));

You can get further help on this topic at this salesforce doc.

4

The object must be the object that matches the HttpCalloutMock class:

Test.setMock(HttpCalloutMock.class, new MockHTTPResponseGenerator());

If you need different responses, they must all come from the respond method, or you need to use different classes for each mock.

global class MockHTTPResponseGenerator implements HttpCalloutMock{
    global HttpResponse respond(HttpRequest req) {
        if(req.getEndpoint().contains('/url1/')) {
            // return response for url1
        } else if(req.getEndpoint().contans('/url2/') {
            // return response for url2
        } // ...
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .