0

I am trying to create a test class for the mentioned class below. I am getting an error while calling the mock call as "Methods defined as TestMethod do not support Web service callouts". Please guide me how to get rid of this error. Right now the test coverage is 30%.

Class :-

Public Class ContactUpdateServer { 
    public Contact objContact{get;set;}
    public String currentRecordId {get;set;}
    public Contact con{get;set;}

    public List<contact> up = new List<Contact>();

    List<ContactCreationCalloutParser.Profile> lstProfilemain = new List<ContactCreationCalloutParser.Profile>() ;

    public ContactUpdateServer(ApexPages.StandardController controller) {
     Boolean isValid = False;
    currentRecordId  = ApexPages.CurrentPage().getparameters().get('id');
        con = [select SSO_Number__c,Name from Contact where id =: currentRecordId ];
        system.debug('----- sso --- ' +con);
        string searchstring = con.SSO_Number__c;
        if(searchString.length() == 9){
                // Check if search string is 9 digit long numeric value. i.e SSO number.
                   if(searchString.isNumeric()){
                     isValid = True;
       }}
       if(isValid){
       system.debug('----isvalid----' +isValid);
        HttpResponse s = ContactServer();
        string token = ParseJSON(s);
        ContactServer1(token);
        }
    }



Public HttpResponse ContactServer() {
        Contact objContact = new Contact();
        system.debug('I am here');

          String strpost='URL';
          HttpRequest reqpost = new HttpRequest();
          HttpResponse respost = new HttpResponse();
          Http htpost=new Http();
          reqpost.setmethod('POST');
          reqpost.setendpoint(strpost);
          respost = htpost.send(reqpost);

         return respost;
         }

 public string ParseJSON(HttpResponse s){
          String resppost = s.getbody();
          System.debug('=====resppost--' + resppost);

          String stoken = TokenParser.parse(resppost).access_token;
          System.debug('--stoken-' + stoken);

          return stoken;
        }
public HttpResponse contactserver1(string stoken){     
        String str ='';
        String authorizationHeader  = 'Bearer ' + stoken;    
        string searchstring = con.SSO_Number__c;
        str ='URL';
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http ht=new Http();

        req.setHeader('Authorization', authorizationHeader);
        req.setmethod('GET');
        req.setendpoint(str);
        res = ht.send(req);
        String resp = res.getbody();
        System.debug('=====resp--'+resp);

        ContactCreationCalloutParser objContactCreation;
        objContactCreation = ContactCreationCalloutParser.parse(resp);
        ContactCreationCalloutParser.Results objResults = objContactCreation.results;
        lstProfilemain = objResults.profile;
        return null;

}


    public Pagereference updateContact(){
       Contact objContact = new Contact();
        for(ContactCreationCalloutParser.Profile objProfile : lstProfilemain) 
              {

                  objContact.Id = ApexPages.CurrentPage().getparameters().get('id');
                  objContact.Supervisorname__c = objProfile.supervisorname;
                  objContact.Type__c = objProfile.type_Z;
                  objContact.title = objProfile.title;
                  objContact.firstname = objProfile.firstname;
                  objContact.lastName = objProfile.lastName;
                  objContact.Email= objProfile.Email;
                  objContact.SSO_Number__c = objProfile.sso;
                  objContact.Phone= objProfile.workphone;
                  objContact.MailingStreet = objProfile.cdilocation;
                  objContact.Business__c = objProfile.business;
                  objContact.Url__c = objProfile.url;
                  objContact.Jobtitle__c = objProfile.jobtitle;
                  objContact.preferredname__c = objProfile.preferredname; 
                  system.debug('----email --- '+ objContact.Email);}
        try {

        update objContact;
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Update Successful'));


        system.debug('---- update success ---');



        }
       catch(DmlException e) 
       {
       System.debug('An unexpected error has occurred: ' + e.getMessage());
       Apexpages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Update Failed. Please Contact Administrator.'));
       }


       return null;


    }

    Public Pagereference Goback(){
    Contact objContact = new Contact();
    objContact.Id = ApexPages.CurrentPage().getparameters().get('id');
    PageReference pageRef = new PageReference('/' + objContact.Id);
     pageRef.setRedirect(true);
      return pageRef;
      }

}

Mock Class :-

@isTest
global class ContactUpdateCalloutTestMock implements HttpCalloutMock {

    global HTTPResponse respond(HTTPRequest req) {

        HttpResponse respost = new HttpResponse();
        respost.setHeader('Content-Type', 'application/json');



        String endPoint = String.valueOf(req.getEndpoint());
        if(endPoint.contains('https://fssfed.stage.ge.com/fss/as/token.oauth2?grant_type'))  
        {   
          respost.setBody('{"access_token":"wXuuiNZlHPz7mtWMaUTKae03r6KN","token_type":"Bearer","expires_in":7199}');
          system.debug('------1---');
        }
        else if(endPoint.contains('https://stage.api.ge.com/digital/search/v1/service?appId='))
        { 
          // To handle blank response
          if(endPoint.contains('123456789')){
              respost.setBody('');
          }
          // To handle exception section
          else if(endPoint.contains('123456780')){
              respost.setBody('{"results":}');
          }
         // To handle original response parsing.
         else{
               respost.setBody('{"results":{"profile":[{"type":"profile","title":"Tester, Pega 9","firstname":"firstTest","lastname":"test","preferredname":"","email":"pega9.tester@ge.com","business":"GE Healthcare","supervisorname":"Surendran, Vrinda","sso":"502066194","url":"http://employeeprofile.ge.com/employeeprofile/people/502066194","jobtitle":"Tester","workphone":"","cdilocation":",US"}]}}');
               }
          }
          respost.setStatusCode(200);
           System.debug('------success');
        return respost;
    }
}

Test class :-

@isTest 
private Class ContactUpdateServerTest{   
@isTest 
Static void test2(){
   Contact objContact = new Contact(lastname = 'test',firstname = 'firstTest', title ='titletest',type__c = 'type',SSO_Number__c = '502066194');
    insert objContact;
      List<ContactCreationCalloutParser.Profile> lstProfilemain = new List<ContactCreationCalloutParser.Profile>() ;


   PageReference pref = Page.ContactUpdateServer;
    pref.getParameters().put('id', objContact.id);
    Test.setCurrentPage(pref);
    ApexPages.StandardController sc = new ApexPages.StandardController(objContact);

    ContactUpdateServer mc = new ContactUpdateServer(sc);

    Test.startTest();
    Test.setMock(HttpCalloutMock.class, new ContactUpdateCalloutTestMock());
     //Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
       HttpResponse res = mc.contactserver();


        // Verify response received contains fake values

      String contentType = res.getHeader('Content-Type');
     system.debug('-----contentType---'+contentType);
       System.assert(contentType == 'application/json');

       String actualValue = res.getBody();

      String expectedValue = '{"access_token":"wXuuiNZlHPz7mtWMaUTKae03r6KN","token_type":"Bearer","expires_in":7199}';

       System.assertEquals(actualValue, expectedValue);

       System.assertEquals(200, res.getStatusCode());

       // GET request

       string s = '57g30E2P5PHZ89eWFiYgDDVpfqqq';
       HttpResponse res1 = mc.contactserver1(s);

        String contentType1 = res1.getHeader('Content-Type');
     system.debug('-----contentType---'+contentType1);
       System.assert(contentType1 == 'application/json');

       String actualValue1 = res1.getBody();

      String expectedValue1 = '{"results":{"profile":[{"type":"profile","title":"Tester, Pega 9","firstname":"firstTest","lastname":"test","preferredname":"","email":"pega9.tester@ge.com","business":"GE Healthcare","supervisorname":"Surendran, Vrinda","sso":"502066194","url":"http://employeeprofile.ge.com/employeeprofile/people/502066194","jobtitle":"Tester","workphone":"","cdilocation":",US"}]}}';


       System.assertEquals(actualValue1, expectedValue1);

       System.assertEquals(200, res1.getStatusCode());

    mc.updateContact(); 

    PageReference result = mc.GoBack();
    System.assertNotEquals(null, result);
    Test.stopTest();
   }
  • 1
    Hey @Karthik, Take a look at the Trailhead module Apex Integration Services. Some pretty good documentation based on what you are looking for. It is one thing getting the answer to your question but you should also take time to understand HTTP and Callout Basics. – TSmith Oct 14 '16 at 12:43
5

Change the position of three lines. You first need to set mock class then declare your constructor because you are making request in your constructor.

Test.startTest();
Test.setMock(HttpCalloutMock.class, new ContactUpdateCalloutTestMock());
ContactUpdateServer mc = new ContactUpdateServer(sc);
  • It worked perfect ! Bingo \m/ – Karthik Oct 14 '16 at 13:24
  • 1
    I am getting one more error now "Attempt to de-reference a null object". Can you please suggest how to write a test case for updatecontact() function ? – Karthik Oct 14 '16 at 13:25
  • 1
    @Karthik you can ask that as different question or provide more details like in which line you are getting this exception. – Tushar Sharma Oct 14 '16 at 16:12
  • how do i mark this as answer ! – Karthik Oct 18 '16 at 1:35
  • @Karthik there is a checkbox sign under my answer upvote count. You can click that and accept this answer. – Tushar Sharma Oct 18 '16 at 2:31

Your Answer

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

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