-2

I am trying to test my Apex class, getting following error response "Methods defined as TestMethod do not support Web service callouts"

public with sharing  class CreateOrder {
private Boolean failed = false;
private Integer responseCode;  
private string atlasUserToken;
private string authToken;
private string redirUrl;


public CreateOrder(ApexPages.StandardController controller) {
    Http h = new Http();
    String url ='https://testurl/users/get_temp_token';    
    HttpRequest  req = buildWebServiceRequest(url);
    HttpResponse  res = invokeWebService(h,req); 
    handleWebServiceResponse(res.getBody().trim());       
}

// Overloaded constructor for test class
public CreateOrder() {        
}

public void handleWebServiceResponse(String response) {
    JSONParser parser = JSON.createParser(response);
    Map<String, Object> jsonMap = new Map<String, Object>();
    try{
        jsonMap = (Map<String, Object>)System.JSON.deserializeUntyped(response);
    }catch(System.JSONException e){
        this.failed =false; 
    }

    authToken = (String)jsonMap.get('auth_token');   
    List<Contact> contactList = [SELECT FirstName,LastName,MailingCity,MailingPostalCode,MailingState,MailingStreet,Phone,Email,Account.Name FROM Contact WHERE AccountId=:ApexPages.currentPage().getParameters().get('ID')];
    Integer size = contactList.size();
    System.Debug('ListSize: ' + size);
    if( size > 0 ) {    
        for(Contact c:contactList){
            redirUrl='https://testurli.com/salesforce/proposal?&request_for=create_order&api_call=true&address1='+c.MailingStreet + '&address2=&city='+c.MailingCity+'&companyName='+c.Account.Name+'&email='+c.Email +'&firstName='+c.FirstName+'&lastName='+c.LastName+'&phone='+c.Phone+'&state='+c.MailingState+ '&zipcode=' + c.MailingPostalCode + '&temp_auth_token=' +authToken;
            this.failed =true; 
        }
    } else  {
        this.failed =false;   
    }
}

public HttpRequest buildWebServiceRequest(String url) {
    //Build HTTP Request object
    //JSONGenerator gen = JSON.createGenerator(true);    
    //gen.writeStartObject();             
    User u = [select Atlas_User_Token__c from user where id=:userinfo.getuserid()];
    atlasUserToken = u.Atlas_User_Token__c;         
    String jsonS;        
    jsonS = JSON.serialize(
        new Map<String, String> {                     
            'user_token' => atlasUserToken
                });

    // Sending the http body with JSON 
    HttpRequest req = new HttpRequest();
    req.setEndpoint(url);
    req.setMethod('POST');
    req.setHeader('Content-Type', 'application/json;charset=UTF-8');
    req.setbody(jsonS); 
    System.debug(req);
    return req;
}

public HttpResponse invokeWebService(Http h, HttpRequest req) {
    //Invoke Web Service
    HttpResponse res = h.send(req); 
    return res;        
}

public PageReference getRedir() {  
    HttpRequest  req;
    HttpResponse res;
    if (!this.failed) {
        // ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Sorry.  We got ' + responseCode + 'Response Code from atlas. <Br/>Current PageId==>'  + ApexPages.currentPage().getParameters().get('ID') +'Current UserId ==>' + UserInfo.getUserId()+ ' Atlas User Token==>' +AtlasUserToken +'  Please try again later.'));
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Sorry.  We got '+ responseCode + ' error Response from atlas. Please Contact System Administrator or try again later.'));
        return null;
    } else {       
        //ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Sorry.  We got '+ ApexPages.currentPage().getParameters().get('ID') + ' error Response from atlas. Please Contact System Administrator or try again later.'));
        PageReference newPage = new PageReference(redirUrl);
        newPage.setRedirect(true);
        return newPage;     
        //return null;           
    }

}

}

Test Class

@isTest
public class testsk {
@isTest
static void test(){
    SetupTest st = new SetupTest();

    //Billing Account
    Account billing = st.Account('Billing');
    billing.Name = 'Test_BillingAccount';
    billing.Atlas_Id__c = 'a_' + billing.Name;
    billing.ParentId = '001m000000kAanaAAC';
    billing.BillingStreet = '7450 Warren pkwy';
    billing.BillingCity = 'Frisco';
    billing.BillingState = 'TX';
    billing.BillingPostalCode = '75034';
    billing.BillingCountry = 'USA';
    billing.ShippingStreet = '7450 Warren pkwy';
    billing.ShippingCity = 'Frosco';
    billing.ShippingState = 'TX';
    billing.ShippingPostalCode = '75034';
    billing.ShippingCountry = 'USA';
    insert billing;

    Contact NewContact = new Contact (
        FirstName = 'xyzFirst',
        LastName = 'XyZLast',            
        AccountId = string.valueOf(billing.Id),
        Email = 'xyzmail@mail.com',
        Phone = '1234567890'
    );         
    insert newContact;

    PageReference pageRef = Page.CreateSalesOrder;
    pageRef.getParameters().put('id',string.valueOf(billing.Id));
    Test.setCurrentPage(pageRef);

    ApexPages.StandardController stdcontroller = new ApexPages.StandardController(billing);        
    CreateOrder con = new CreateOrder(stdcontroller); 

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

}

public class Response implements HttpCalloutMock{
    public HttpResponse respond(HttpRequest req){
        HttpResponse mockResponse = new HttpResponse();
        mockResponse.setHeader('Content-Type', 'application/json');
        mockResponse.setStatusCode(200);
        mockResponse.setBody('{"auth_token": "e963a669e30a815983b9dab6fe688b516299b2d0e2927e1119b0f4874394f3ce8e963216799d443ac55fdd9ddf240db7d732ca350e0e5d9b3ff29a207086b2132f37ecd52e1043d02a62b0be4d2afd68d2457ba8b3f4aa4a7a197b9b28229f12b5f6efd0", "expires_on": "2018-09-21T10:37:04.271Z"}');
        return mockResponse;
    }
}

}

enter image description here

0
1

You will need to add a class which implements one of the CalloutMock interfaces, in this case HttpCalloutMock would work. This will spoof pre-written responses to your http requests in the test environment.

Details on how this is setup are here;- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm

You can have it send different responses based on the request details but in this case you will just need it to return a response with a json body including the 'auth-Token' key-value pair to cover your handler code.

Once the class is written you will need to instantiate it in your test class by adding the SetMock method and then you should be good to go!

0

Test classes do not support Web service callouts. You need to use a CalloutMock class that pretends to make the callout.

3

Not the answer you're looking for? Browse other questions tagged or ask your own question.