0

below is my class code. code is not getting covered for the catch block. current code coverage is 75%. Also given below is my test class code. In need at least 90%.

public class QualtricsEmailDistribution {
    public static Http objhttp;
    public static HttpRequest req ;
    public static HttpResponse res ;

    public void MakeRestCalloutEmail()
        {
            // Custom settings
           List<Qualtrics_Email_Distribution__c> customsettingdata = Qualtrics_Email_Distribution__c.getall().values();
            if(customsettingdata[0].Status__c==true){
               objhttp = new Http();
               req = new HttpRequest();
               res = new HttpResponse();
               req.setMethod('GET');
               req.setHeader('Content-Type', 'application/json;charset=UTF-8');
               //GetDistribution
               String epoint='http://api.salesforce.com/';
               req.setEndpoint(epoint);
               system.debug('After end point');
               // Set the necessary Headers
               String reqBody = '';
               req.setBody(reqBody);
               System.debug('request body'+req); 
                   try {
                            res = objhttp.send(req);

                       }
                            catch(System.CalloutException e) {
                            System.debug('Callout error: '+ e);
                       }
                        system.debug('res'+res);
         if (res.getStatusCode() == 200) {
            Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
            system.debug('results'+results);
            Map<String, Object> resultdata = (Map<String, Object>) results.get('Result');
            system.debug('Key'+resultdata.keySet());
            List<Object> disdata = (List<Object>) resultdata.get('Distributions');
            //system.debug('disdata'+ String.valueOf(disdata[0]));
            system.debug('disdata'+ String.valueOf(disdata));
             system.debug('in loop'+disdata.size());
            Map<Object,Object> finaljsondata = new Map<Object,Object>(); 
             //check heapsize here disdata.size()-1
             for(Integer i=0;i<20;i++){
                 Map<String, Object> emaildistributions = (Map<String, Object>)JSON.deserializeUntyped(JSON.Serialize(disdata[i])); 
                 Object a1=emaildistributions.get('EmailDistributionID');
                 Object a2 = emaildistributions.get('CreatedDate');
                 finaljsondata.put(a1, a2);
           }
            System.debug('finaljsondata'+finaljsondata);
             //Campaign Member data
             list<Campaignmember> cammember = new list<Campaignmember>();
             cammember = [select id,Actual_sent_date__c,Qualtrics_Schedule_Date__c,Qualtrics_Schedule_Reminder1__c,Qualtrics_Schedule_Reminder2__c from Campaignmember where Actual_sent_date__c!=null];
             System.debug('cammember'+cammember);
             for(Object finddate:finaljsondata.values()){
                 system.debug('finddate'+finddate);
         }
             for(Campaignmember cmm:cammember){
                 system.debug('Campaignmember'+cmm.Actual_sent_date__c); 
             }
         }
            }
    }
}
fake response class:-

@isTest
global class FakeResponse implements HttpCalloutMock{
 global static HTTPResponse respond(HTTPRequest req) {
   System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());

        System.assertEquals('GET', req.getMethod());



        // Create a fake response

        HttpResponse res = new HttpResponse();

        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');

        res.setStatusCode(200);

        return res;


    }
}

test class code:-

@isTest
global class TestQualtricsEmailDistribution {
    @isTest static void init() {
        Contact con=new contact();
        con.LastName='vineet';
        insert con;
        Contact cont=[select Id,LastName from Contact where Id=:con.Id];
        Qualtrics_Email_Distribution__c qed= new Qualtrics_Email_Distribution__c();
        qed.Name='qualtrics';
        qed.Library_ID__c='123';
        qed.Status__c=true;
        qed.Qualtrics_User_Id__c='456';
        qed.Survey_ID__c='789';
        qed.Token__c='aaa';
        insert qed;
        Campaign c=new Campaign();
        c.Name='test';
        insert c;
      //  Campaign cp =  [SELECT Id FROM Campaign where Name='test vig' AND IsActive=TRUE LIMIT 1];
      Campaign cp=[SELECT Id, name from Campaign where id=:c.Id];
        Campaignmember cm= new Campaignmember();
        cm.Actual_sent_date__c=datetime.now();
        cm.Qualtrics_Schedule_Date__c=datetime.now();
        cm.Qualtrics_Schedule_Reminder1__c=datetime.now();
        cm.Qualtrics_Schedule_Reminder2__c=datetime.now();
        cm.Status='sent';
       cm.ContactId=cont.Id;
        cm.CampaignId=cp.Id;
        cm.Actual_sent_date__c=datetime.now();
        insert cm;

    }
 /*  global static HTTPResponse respond(HTTPRequest req) {
   System.assertEquals('http://api.salesforce.com/foo/bar', req.getEndpoint());

        System.assertEquals('GET', req.getMethod());



        // Create a fake response

        HttpResponse res = new HttpResponse();

        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"foo":"bar"}');

        res.setStatusCode(200);

        return res;


    }*/
     @isTest static void testCallout() {
        TestQualtricsEmailDistribution.init();
        FakeResponse fr= new FakeResponse();
        Test.setMock(HttpCalloutMock.class, fr);


         //Verify response received contains fake values

     // String contentType = re.getHeader('Content-Type');

        //  System.assert(contentType == 'application/json');

      // String actualValue = re.getBody();
       // String expectedValue = '{"foo":"bar"}';

       // System.assertEquals(actualValue, expectedValue);

       // System.assertEquals(200, re.getStatusCode());

     QualtricsEmailDistribution qed=new QualtricsEmailDistribution();


           qed.MakeRestCalloutEmail();   


     }
}
  • Keep in mind that coverage is not the primary goal of unit tests (the primary goal is to verify that your code produces expected output). That said, are you sure that your catch block isn't covered? The way I see it, you should absolutely be getting into the catch block of the code you're testing because you haven't made a mock for your callout. If you weren't, it certainly wouldn't be enough to 90% coverage. – Derek F Apr 27 '17 at 12:49
  • I'd suggest reading Testing Http Callouts by implementing HttpCalloutMock – Derek F Apr 27 '17 at 12:50
  • Not to mention the assert in the catch is useless. If the exception is unexpected you should not be catching it. If the exception is expected you should be asserting that the type is what you expect or throw another exception. If you focus on writing proper test methods your coverage will come organically – Eric Apr 27 '17 at 13:33
  • @derek thanks for the info. i followed as u told. now actually its coming inside catch block but not able to go beyond Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody()); – vineet Apr 27 '17 at 13:35
  • @eric yes you are right i removed it and the code coverage is still the same. thnx. kindly also let me know how to cover the deserializaion of response. i mean the line Map<String, Object> results = (Map<String, Object>)JSON.deserializeUntyped(res.getBody()); – vineet Apr 27 '17 at 13:37

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.