+ Start a Discussion
Salesforce Developer 60Salesforce Developer 60 

Test Class for Webservice

Hello ,
         I create a webservice for consuming rest api from .net . I am facing issue in test class for this . It's gives error callout not allowed from test method. How to write test class for below controller.
 
public with sharing class WebserviceCall {

    public WebserviceCall(ApexPages.StandardController controller) {

    }

    public String message {get; set;}
    
    public PageReference getaccesstoken() { 
      string jsonstring ='userName=test@gmail.com&Password=123&grant_type=password';
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
       // req.setClientCertificateName('Client Certificate');
       
        req.setEndpoint('http://google.com');
        req.setMethod('POST');
       // req.setHeader('SOAPAction', 'Soap Action');
        //req.setHeader('Authorization','Auth Token');
      
       req.setBody(jsonstring);
 
           try {
            res = http.send(req);
            message = res.getBody();
    TokenInformation token = new TokenInformation();
    token =(TokenInformation)System.JSON.deserialize(message, TokenInformation.class);
  // JSONParser parser = JSON.createParser(res.getBody());
            System.debug(token.access_token);
                 //HttpServletResponse httpResponse = (HttpServletResponse)response;
              string s = token.access_token;
            string a1 = s.substring(0,255);
            string a2 = s.substring(255,510);
            string a3 =s.substring (510,s.length());
            //Here SessionData__c is custom setting used for store access_token
       SessionData__c objToken = new SessionData__c();
       objToken.Name ='token2';
       objToken.Id ='a0G28000000ENAI';
    objToken.Access_Token1__c =a1;objToken.Access_Token2__c =a2;
               objToken.Access_Token3__c =a3;

upsert objToken;
               
        } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
             message = res.toString() + res.getBody();
            System.debug(res.toString());
        }
        return null;
        
}       
    
    
    
    
}

Best Answer chosen by Salesforce Developer 60
Shrikant BagalShrikant Bagal
Please try following 

/* MockResponse class implementing the HttpCalloutMock interface */
-----------------------------------------------------------------------------------------------------------------------------------------------------
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
   // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://google.com', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
  
       // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"access_token":"8UT28QKGORMivFqne-6PMRLdTYk3AS0mcxdVwRJEwYsTjwZjqGopk1TRzGX7vHSZpFNFL3HOmX3RKZrQkBap3b16j-XVkwArdDbhusArOBGzYsD1cpA8B87N_RedJrd9btvq2i22cAjPvyJLSVMc297U0V9YZ9rJ3tM429G8mglnsUNUVJJi_nnTJAN6-H038B4Y1aQeRQZVdU72Nr942eYZ3fXv1HXfxwYUZgWyYO5juVaVnoq_ZJHcrFGXfNp5LVrNlnEibHhJ2RGeD-MYKhyVjfkTrATGQhYY--OVCOemUyWKTlwgwBFjgzfpQfOq79raEglOTgEF3Qx78RY2-nBNvgOTRMET4B2fT17Q8EN4UCQLxGZTGq1ACN5j2B3YKT7isjzwAgysloYGJsL4j4D8dCGKgWBO0rTXwx7MfkNsX5TjAYRNCip5vTSRXeSBqhjM_TtwbKCA0HexikSz-XryZT7pKGYhjfRCXtWudd7OUjFYoDRfKTiAhjNk5yJj","token_type":"bearer","expires_in":86400,"userName":"test@gmail.com",".issued":"Thu, 25 Jun 2015 12:56:23 GMT",".expires":"Fri, 26 Jun 2015 12:56:23 GMT"}');
        res.setStatusCode(200);
        return res;
    }
}



----------------------------------------------------------------------------------------------------------------------------------------------------------------
/* Test Class getting fake response  from the class MockHttpResponseGenerator that implements HttpCalloutMock */
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
       // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());  
       // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock.
        PageReference pageRef = new WebserviceCall().getaccesstoken();
    }
}



Please mark as best answer so it will help to other who will serve same problem.
​Thanks!


 

All Answers

Shrikant BagalShrikant Bagal
Hello SF developer 60,

To test the Callout you need to create an Mock class please refer following links :

- https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_wsdl2apex_testing.htm

Hope its help!!!

Thanks!
 
Salesforce Developer 60Salesforce Developer 60
@Arunkumar , which wrapper class i share with you ??  below is my json response which i receive .

 
{"access_token":"8UT28QKGORMivFqne-6PMRLdTYk3AS0mcxdVwRJEwYsTjwZjqGopk1TRzGX7vHSZpFNFL3HOmX3RKZrQkBap3b16j-XVkwArdDbhusArOBGzYsD1cpA8B87N_RedJrd9btvq2i22cAjPvyJLSVMc297U0V9YZ9rJ3tM429G8mglnsUNUVJJi_nnTJAN6-H038B4Y1aQeRQZVdU72Nr942eYZ3fXv1HXfxwYUZgWyYO5juVaVnoq_ZJHcrFGXfNp5LVrNlnEibHhJ2RGeD-MYKhyVjfkTrATGQhYY--OVCOemUyWKTlwgwBFjgzfpQfOq79raEglOTgEF3Qx78RY2-nBNvgOTRMET4B2fT17Q8EN4UCQLxGZTGq1ACN5j2B3YKT7isjzwAgysloYGJsL4j4D8dCGKgWBO0rTXwx7MfkNsX5TjAYRNCip5vTSRXeSBqhjM_TtwbKCA0HexikSz-XryZT7pKGYhjfRCXtWudd7OUjFYoDRfKTiAhjNk5yJj","token_type":"bearer","expires_in":86400,"userName":"test@gmail.com",".issued":"Thu, 25 Jun 2015 12:56:23 GMT",".expires":"Fri, 26 Jun 2015 12:56:23 GMT"}

 
Salesforce Developer 60Salesforce Developer 60
@Shrikant , I already see this link but am not able to solved out this . How to do start with this class.
Ajay K DubediAjay K Dubedi
Hi...
For a WebService CallOutclass Please follow the link:-http://http://learningthecloudway.blogspot.in/2013/10/how-to-create-mock-http-response-in.html
 Try this and mark as best if it helps for you
 
Shrikant BagalShrikant Bagal
Please try following 

/* MockResponse class implementing the HttpCalloutMock interface */
-----------------------------------------------------------------------------------------------------------------------------------------------------
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
   // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://google.com', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
  
       // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"access_token":"8UT28QKGORMivFqne-6PMRLdTYk3AS0mcxdVwRJEwYsTjwZjqGopk1TRzGX7vHSZpFNFL3HOmX3RKZrQkBap3b16j-XVkwArdDbhusArOBGzYsD1cpA8B87N_RedJrd9btvq2i22cAjPvyJLSVMc297U0V9YZ9rJ3tM429G8mglnsUNUVJJi_nnTJAN6-H038B4Y1aQeRQZVdU72Nr942eYZ3fXv1HXfxwYUZgWyYO5juVaVnoq_ZJHcrFGXfNp5LVrNlnEibHhJ2RGeD-MYKhyVjfkTrATGQhYY--OVCOemUyWKTlwgwBFjgzfpQfOq79raEglOTgEF3Qx78RY2-nBNvgOTRMET4B2fT17Q8EN4UCQLxGZTGq1ACN5j2B3YKT7isjzwAgysloYGJsL4j4D8dCGKgWBO0rTXwx7MfkNsX5TjAYRNCip5vTSRXeSBqhjM_TtwbKCA0HexikSz-XryZT7pKGYhjfRCXtWudd7OUjFYoDRfKTiAhjNk5yJj","token_type":"bearer","expires_in":86400,"userName":"test@gmail.com",".issued":"Thu, 25 Jun 2015 12:56:23 GMT",".expires":"Fri, 26 Jun 2015 12:56:23 GMT"}');
        res.setStatusCode(200);
        return res;
    }
}



----------------------------------------------------------------------------------------------------------------------------------------------------------------
/* Test Class getting fake response  from the class MockHttpResponseGenerator that implements HttpCalloutMock */
@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
       // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());  
       // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock.
        PageReference pageRef = new WebserviceCall().getaccesstoken();
    }
}



Please mark as best answer so it will help to other who will serve same problem.
​Thanks!


 
This was selected as the best answer
Shrikant BagalShrikant Bagal
Hello @Salesforce Developer 60,

Please mark as best answer so it will help to other who will serve same problem.
​Thanks!

 
Shrikant BagalShrikant Bagal
Could you please add Screenshot of code covrage of class?
Salesforce Developer 60Salesforce Developer 60
Find screenshot for class. This part is not cover in test class. For full class see above question.
User-added image
Shrikant BagalShrikant Bagal
As per screen-shot we get an Callout exception, could you please post that exception at line : 81
 
Salesforce Developer 60Salesforce Developer 60
@Shrikant, am not getting your point. Where i post and what exception?
Shrikant BagalShrikant Bagal
As per the code covrage screenshot the 

catch(System.CalloutException e){
  message = res.toString() + res.getbody();
}

is Covered that mean, the response have some issue, to solve it we need that message.
Salesforce Developer 60Salesforce Developer 60
Yes message is not getting response here. So what  change should i do for that.
Shrikant BagalShrikant Bagal
you can print an error by adding following line in your CalloutException Catch block
 
syste.debug('Callout Exception: ' + e.getMessage());

 
Shrikant BagalShrikant Bagal
its 
 
system.debug('Callout Exception: ' + e.getMessage());

 
Salesforce Developer 60Salesforce Developer 60
I add this line but it's display nothing there. And more question  i want to run this class daily 2 am so below is right class.
 
global class scheduledWebServiceCall implements Schedulable {
   global void execute(SchedulableContext sc) {
   Account a;
   Apexpages.Standardcontroller controller_inv = new Apexpages.Standardcontroller(a);
      WebserviceCall b = new WebserviceCall(controller_inv); 
      b.getaccesstoken();
   }
}

 
Shrikant BagalShrikant Bagal
yes,

Please check for line System.debug('Callout error : ' + e)
Salesforce Developer 60Salesforce Developer 60
I make some changes in my class  and add this so now coverage is 94%. Verify that it's right way?
 
public static HTTPResponse respond(HTTPRequest req) {
       
       // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setStatusCode(200);
        res.setBody('{"access_token":"jcTZV6qVLzUsMfuQI27CUXbsgAkKkZnK2pGjqt6eQtHbTLdtR4hA7_zR8bPwMTugRoDAIIGmLHjKP76_xf2FCYDPwqWKBcDCKSugHcSfXT0MvcLGdauQi0iyn_e6xtEI58vIl7cKb_GM6X53ouE8NxKtYBgGDimwU8qAS9_FGTc70X2LGm5KJPUKMHWsukOp3uQ-x3qePixLF0GwSBrp4hHPs_hizxTBsKejJqH0ijEnWn7AivipY9UEWHS5iJ1k_UfLpVib83FikG-Uvq5Ejg5WqPxijGTyrrmUWvpS-ODzAWI53pENe9XxPUWhzt1pIYxz9P_ETKVydf0EAVScL7ejwYo3_DldjVRA7QbcxV9I483PdUxF9pA7Og1No9bh_ubQGIBHeOrPrFOhdgKZLMX4_Rn5hkTXqqY4kKKcfcuHQ-DRsBVrgBwwlC0zhsyhzY2sQIGZOjVpMxpNwvk5pjy8zI6pbKYz6BAlLKGUkot0eyVkmgCRM5jwdC9fxxqg","token_type":"bearer","expires_in":86400,"userName":"pritam.shekhawat@hytechpro.com",".issued":"Sun, 28 Jun 2015 11:40:31 GMT",".expires":"Mon, 29 Jun 2015 11:40:31 GMT"}');
        
        system.debug(res.getBody());
        return res;
    }   
    
    
}

So now catch(System.CalloutException e) and message =  res.getBody(); not coverage.
Shrikant BagalShrikant Bagal
cool.
please mark as best answer so it will help to other who will serve same problem.
​Thanks! 
Salesforce Developer 60Salesforce Developer 60
Thanks for support :)
Salesforce Developer 60Salesforce Developer 60
@Shrikant, I have some other API classs . For this i have to again create two test class as above ??
Shrikant BagalShrikant Bagal
yes :)