1

I have some test classes that run decently until they hit something like

HTTResponse res =  h.send(req);

Where I then get 'System.UnexpectedException: Script-thrown exception'. I make a few different callouts in my code.

I am using the HttpCalloutMock class as well, although probably incorrectly.

@isTest
public static void test1() {
    Lead l = [SELECT Id, Name, Phone, Email, from Lead WHERE Name = ‘Test 123’];

    SingleRequestMock token = new SingleRequestMock(200, 'OK','[{"Name": "sForceTest1"}]', null);
    SingleRequestMock banner = new SingleRequestMock(200, 'OK', '[{"LastName": "Test Last Name"}]', null);
    SingleRequestMock person = new SingleRequestMock(200, 'OK', '[{"LastName": "Test Last Name"}]', null);

    Map<String, HttpCalloutMock> e = new Map<String, HttpCalloutMock>();
    e.put('https://url1.com/testing’, token);
    e.put('https://url2.com/testing', lead);
    e.put('https://url3.com/testing', account);

    HttpCalloutMock MultiMock = new MultiMock(e);

    Test.setMock(HttpCalloutMock.class, MultiMock);
    PageReference pageRef = Page.BannerDuplicationManagement;
    Test.setCurrentPage(pageRef);
    MainClass ctrl = new MainClass();
    ctrl.leadId = l.Id;
    ctrl.message = 'message';
    ctrl.msg = 'msg';
    ctrl.rerun();
    //System.assertEquals(/*check for expected results here...*/);
}

And

@isTest
global class MultiMock implements HttpCalloutMock {
Map<String, HttpCalloutMock> requests;

public MultiMock(Map<String, HttpCalloutMock> requests) {
    this.requests = requests;
}

public HTTPResponse respond(HTTPRequest req) {
    HttpCalloutMock mock = requests.get(req.getEndpoint());
    if (mock != null) {
        return mock.respond(req);
    } else {
        System.debug('HTTP callout not supported for test methods');
        return null;
    }
}

public void addRequestMock(String url, HttpCalloutMock mock) {
    requests.put(url, mock);
}
}

Thank you!

  • 1
    What was the thrown exception? Everything here looks okay to me. – sfdcfox Jan 30 '18 at 18:25
  • Every single time the test hits: HttpResponse res = h.send(req); String body = res.getBody(); I get stuck on the res = h.send(req); req being the endpoint: // Set HTTPRequest Method + Endpoint . req.setEndpoint(url); req.setMethod('POST'); // Headers req.setHeader('Accept', 'application/json'); req.setHeader('Content-Type', 'application/json'); req.setHeader('Accept-Language', 'en-US'); req.setHeader('Authorization', 'Bearer ' + token); req.setTimeout(120000); – JimKasper99 Jan 30 '18 at 18:42
  • 1
    Sometimes you are returning a null response. So if your test assumes the response is non-null, it's no surprise you hit exceptions. Just would have expected a NullPointerException. – Adrian Larson Jan 30 '18 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.