function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Anish Mahadik 1Anish Mahadik 1 

Test class for http request

Hi All,

I am facing an issue with test class .We have done the integration with mule sytsem.

Apex class

private static List<String> GDMSWebService (Id enqId,Integer fileIndex)
    {
        List<String> responses = new List<String>();
        String docString;
        String urlString;
        String referenceNo;
        List<Attachment> attach = new List<Attachment>();
        GDMSFileWrapperList wraplist= new GDMSFileWrapperList();
        HttpRequest req = new HttpRequest();
        
        MuleEndpoint__c setting = MuleEndpoint__c.getValues('MuleEndPoint');
        // Specify the required user name and password to access the endpoint
        // As well as the header and header information
        req.setEndpoint(setting.MuleUploadEndpoint__c);
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');
        
        attach = [SELECT Id,ParentID,name,ContentType,BodyLength,Body FROM Attachment where ParentID = :enqId];
        system.debug('attach in GDMS' + attach);
        if (fileIndex > attach.size() - 1)
        {
            system.debug('GDMSWebService, fileIndex > attach.size - 1, do nothing ' + attach.size());
            responses.add('No ID');
            responses.add('GDMSWebService, fileIndex > attach.size - 1, do nothing');
            return responses;
        }
        
        wraplist.Body = EncodingUtil.base64Encode(attach[fileIndex].Body);
        wraplist.fileName = attach[fileIndex].name;
        
        ContactUs_Enquiry__c enq = [SELECT id, name,
                                   File1_DocumentIdReturnString__c, File1_UrlReturnString__c,
                                   File2_DocumentIdReturnString__c, File2_UrlReturnString__c,
                                   File3_DocumentIdReturnString__c, File3_UrlReturnString__c
                                   from ContactUs_Enquiry__c where id = :enqId];
        
        String authorizationHeader = setting.MuleHeader__c;
        req.setHeader('Authorization', authorizationHeader);
        // Specify the required user name and password to access the endpoint
        // As well as the header and header information
        referenceNo = enq.Name;
        String body ='{'+
            '"ServiceInvoker": "SG_SF",'+ //wraplist.ServiceInvoker +
            '"CountryCode": "SG",'+ //wraplist.CountryCode +
            '"ImportDocument": { '+
            '"fileContent":"'+wraplist.Body +'",'+
            '"fileName": "'+wraplist.fileName +'",'+
            '"DocMetadataForImportingDoc": { '+
            '"DocMetadataForImportingDocType": { '+
            '"DocDs": "Application",'+ // wraplist.DocDs +
            '"SubDocDs": "Application", '+ //wraplist.SubDocDs +
            '"SubmissionNo": "'+referenceNo +'"'+
            ' }'+
            ' }'+
            ' }'+
            '}';
        
        req.setBody(body);
        System.debug('GDMSWebService, request Body ' + body);
        //System.debug('GDMSWebService, request ' + req);
        
        // Create a new http object to send the request object
        // A response object is generated as a result of the request  
        docString = '';
        urlString = '';
        Http http = new Http();
        Integer setTime = Integer.ValueOf(setting.SetTimeOut__c);
        req.setTimeout(setTime);
        HTTPResponse res = http.send(req);
        //System.debug('GDMSWebService, response ' + res);
        System.debug('GDMSWebService, response body ' +res.getBody());
        
        //deserialize json body to fetch UrlReturnString & DocumentIdReturnString
        try
        {
            if (res.getStatusCode() == 200)
            {    
                String strjson = res.getbody();
                Map<String,Object> m = (Map<String,Object>)JSON.deserializeUntyped(strjson);
                //system.debug('GDMSWebService, m ' +m);
                Map<String,Object> importdoc = (Map<String, Object>)m.get('ImportDocumentReturnType');
                //system.debug('GDMSWebService, importdoc ' +importdoc);
                docString = String.valueOf(importdoc.get('DocumentIdReturnString'));
                urlString = String.valueOf(importdoc.get('UrlReturnString'));
                System.debug('GDMSWebService, res.getStatusCode() == 200');
                System.debug('GDMSWebService, docString '+docString);
                System.debug('GDMSWebService, urlString '+urlString);
            }
            else
            {
                docString = String.valueOf(res.getStatusCode());
                urlString = 'GDMSWebService Error, res.getStatusCode() <> 200';
                System.debug('GDMSWebService, res.getStatusCode() <> 200');
                System.debug('GDMSWebService, docString '+docString);
                System.debug('GDMSWebService, urlString '+urlString);
            }
        }
        catch (System.CalloutException ex)
        {
            System.debug('GDMSWebService, exception ' + ex.getMessage() + ' on line ' + ex.getLineNumber());
            docString = String.valueOf(ex.getLineNumber());
            urlString = 'GDMSWebService Error, exception ' + ex.getMessage();
            System.debug('GDMSWebService, docString exception '+docString);
            System.debug('GDMSWebService, urlString exception '+urlString);
        }
        
        responses.add(docString);
        responses.add(urlString);
        return responses;
    }
    


Test class

static testMethod void testMethodrequest(){ 
          
        User usr = [Select id, Username from User where Username = 'uniqueName@test.com' limit 1];
        MuleEndpoint__c endpoint = [Select Id,GDMSLinkInRouteEmail__c,MuleHeader__c,SetTimeOut__c,MuleUploadEndpoint__c from MuleEndpoint__c where GDMSLinkInRouteEmail__c=true LIMIT 1];

        System.runAs(usr){
        Boolean GDMSLinkInRouteEmail =  endpoint.GDMSLinkInRouteEmail__c;       
        List<EmailServiceMasterData__c> custList = new List<EmailServiceMasterData__c>();    
        EmailServiceMasterData__c cust = new EmailServiceMasterData__c();
        cust.name = 'TestRec1';
        cust.Allow_Upload_Attachments__c = true;
        cust.Policy_Type__c ='Auto Insurance'; 
        cust.Query_Type__c ='Claims';
        cust.AckType__c = '5';
        cust.Product__c = '';
        cust.GDMSDocType__c = '';
        cust.EnquiryBy__c = 'B';
        cust.Type_of_Incident_Creation__c = 'Service Incident';
        cust.Routed_to_Mailbox__c='test@aig.com;test1@aig.com';
        cust.Salesfoce_Queue__c = 'CAutoQ';
        cust.Need_Incident_Creation__c = true;
        cust.Product__c = '';
        custList.add(cust);    
        
        EmailServiceMasterData__c cust1 = new EmailServiceMasterData__c();    
        cust1.name = 'TestRec2';
        cust1.Allow_Upload_Attachments__c = true;
        cust1.Policy_Type__c ='Auto Insurance'; 
        cust1.Query_Type__c ='Claims';
        cust1.AckType__c = '5';
        cust1.Product__c = '';
        cust1.GDMSDocType__c = '';
        cust1.EnquiryBy__c = 'B';
        cust1.Type_of_Incident_Creation__c = 'Service Incident';
        cust1.Routed_to_Mailbox__c='test44@aig.com;test1@aig.com';
        cust1.Salesfoce_Queue__c = 'CAutoQ';
        cust1.Need_Incident_Creation__c = true; 
        cust1.Product__c = '';
        custList.add(cust1);    
        insert custList;
        
        List<ContactUs_Enquiry__c> conlist = new List<ContactUs_Enquiry__c>();    
        ContactUs_Enquiry__c con = new ContactUs_Enquiry__c();
        con.EnquiryBy__c ='Broker/Agent';
        con.CustomerType__c='Individual';
        con.PolicyType_Agent__c='Auto Insurance';
        con.Nature_Agent__c='Claims';
        con.Producer_Cd__c='test001';
        con.Producer_Name__c='test';
        con.Prod_Mobile__c='84345553';
        con.Prod_Email__c='test@aig.com';
        con.Customer_Name__c='Sconty Test';
        con.NRIC__c='9999999';
        con.Policy_No__c='45565432';
        con.Cust_Phone__c='54554533';
        con.Cust_Email__c='test@aig.com';
        con.Enquiry_Detail__c='Test';
        con.Cust_Address__c = 'Sing';
        con.Cust_PostCode__c = '878987';
        con.File1__c = 'Test001.jpg';
        con.File2__c = 'Dummy File.docx';
        con.File3__c = 'test10.csv'; 
        con.File1_UrlReturnString__c = 'https://cmicdev.aig.net:9444/icmrm/ICMResourceManager/Test001.jpg?order=retrieve&item-id=A1001001A23A10A45213I21897&version=1&collection=APAC.CLLCT001&libname=ICMNLSDB&update-date=2023-01-10+09%3A52%3A14.389201000&token=ADUA.MvzMHuJYx7U2_06dTHEwkVgRp9dS292THJgQRbxHW2oSMW7TNoiv2U2x;&content-length=0&content-type=image%2Fjpeg';
        con.File2_UrlReturnString__c = 'https://cmicdev.aig.net:9444/icmrm/ICMResourceManager/Dummy%20File.docx?order=retrieve&item-id=A1001001A23A10A45220D21899&version=1&collection=APAC.CLLCT001&libname=ICMNLSDB&update-date=2023-01-10+09%3A52%3A21.167205000&token=ADUA.MvzMJeJZ1z_2_4TlmLMS5K4JByyZPECycJXRRe3IL94_GTVScEBI77.6;&content-length=0&content-type=application%2Fvnd.openxmlformats-officedocument.wordprocessingml.document';
           con.File3_UrlReturnString__c = 'https://cmicdev.aig.net:9444/icmrm/ICMResourceManager/test10.csv?order=retrieve&item-id=A1001001A23A10A45220D21899&version=1&collection=APAC.CLLCT001&libname=ICMNLSDB&update-date=2023-01-10+09%3A52%3A21.167205000&token=ADUA.MvzMJeJZ1z_2_4TlmLMS5K4JByyZPECycJXRRe3IL94_GTVScEBI77.6;&content-length=0&content-type=application%2Fvnd.openxmlformats-officedocument.wordprocessingml.document';
        conlist.add(con);
            
        ContactUs_Enquiry__c con1 = new ContactUs_Enquiry__c();
        con1.EnquiryBy__c ='Broker/Agent';
        con1.CustomerType__c='Corporate';
        con1.PolicyType_Agent__c='Auto Insurance';
        con1.Nature_Agent__c='Claims';
        con1.Producer_Cd__c='test001';
        con1.Producer_Name__c='test';
        con1.Prod_Mobile__c='84345553';
        con1.Prod_Email__c='test@aig.com';
        con1.Customer_Name__c='Sconty V';
        con1.NRIC__c='9999999';
        con1.Policy_No__c='45565432';
        con1.Cust_Phone__c='54554533';
        con1.Cust_Email__c='test@aig.com';
        con1.Enquiry_Detail__c='Test';
        con1.Cust_Address__c = 'Sing';
        con1.Cust_PostCode__c = '878987';
        con1.File1__c = 'Test001.jpg';
        con1.File2__c = 'Dummy File.docx';
        con1.File3__c = 'test10.csv';    
        con1.File1_UrlReturnString__c = 'https://cmicdev.aig.net:9444/icmrm/ICMResourceManager/Test001.jpg?order=retrieve&item-id=A1001001A23A10A45213I21897&version=1&collection=APAC.CLLCT001&libname=ICMNLSDB&update-date=2023-01-10+09%3A52%3A14.389201000&token=ADUA.MvzMHuJYx7U2_06dTHEwkVgRp9dS292THJgQRbxHW2oSMW7TNoiv2U2x;&content-length=0&content-type=image%2Fjpeg';
        con1.File2_UrlReturnString__c = 'https://cmicdev.aig.net:9444/icmrm/ICMResourceManager/Dummy%20File.docx?order=retrieve&item-id=A1001001A23A10A45220D21899&version=1&collection=APAC.CLLCT001&libname=ICMNLSDB&update-date=2023-01-10+09%3A52%3A21.167205000&token=ADUA.MvzMJeJZ1z_2_4TlmLMS5K4JByyZPECycJXRRe3IL94_GTVScEBI77.6;&content-length=0&content-type=application%2Fvnd.openxmlformats-officedocument.wordprocessingml.document';
        con1.File3_UrlReturnString__c = 'https://cmicdev.aig.net:9444/icmrm/ICMResourceManager/test10.csv?order=retrieve&item-id=A1001001A23A10A45220D21899&version=1&collection=APAC.CLLCT001&libname=ICMNLSDB&update-date=2023-01-10+09%3A52%3A21.167205000&token=ADUA.MvzMJeJZ1z_2_4TlmLMS5K4JByyZPECycJXRRe3IL94_GTVScEBI77.6;&content-length=0&content-type=application%2Fvnd.openxmlformats-officedocument.wordprocessingml.document';
        conlist.add(con1);
        insert conlist;
        
        List<Attachment> attachList = new List<Attachment>();
        Blob b = Blob.valueOf('Test Data.txt');
        Attachment attach = new Attachment();
        attach.ParentId = con.id;
        attach.Name = 'Test Attachment 0';
        attach.Body = b;
        attachList.add(attach);
            
        Blob b1 = Blob.valueOf('Test Data.txt');    
        Attachment attach1 = new Attachment();
        attach1.ParentId = con.id;
        attach1.Name = 'Test Attachment 1';
        attach1.Body = b1;
        attachList.add(attach1);
            
        Blob b2 = Blob.valueOf('Test Data.txt');    
        Attachment attach2 = new Attachment();
        attach2.ParentId = con.id;
        attach2.Name = 'Test Attachment 2';
        attach2.Body = b2;  
        attachList.add(attach2);    
        insert attachList;
            
        GDMSFileWrapperList wraplist= new GDMSFileWrapperList();
        wraplist.Body = EncodingUtil.base64Encode(attachList[0].Body);
        wraplist.fileName = attachList[0].name;    
            
           
        Integer fileIndex = 1;
        RestRequest req = new RestRequest(); 
           RestResponse res = new RestResponse();
        
        String testJson ='{'+
            '"ServiceInvoker": "SG_SF",'+
            '"CountryCode": "SG",'+ 
            '"ImportDocument": { '+
            '"fileContent":"'+wraplist.Body +'",'+
            '"fileName": "'+wraplist.fileName +'",'+
            '"DocMetadataForImportingDoc": { '+
            '"DocMetadataForImportingDocType": { '+
            '"DocDs": "Application",'+ // wraplist.DocDs +
            '"SubDocDs": "Application", '+ //wraplist.SubDocDs +
            '"SubmissionNo": "'+con.Name +'"'+
            ' }'+
            ' }'+
            ' }'+
            '}';
            
        req.requestURI = endpoint.MuleUploadEndpoint__c;
        req.httpMethod = 'POST';
        req.addHeader('Content-Type', 'application/json');
        RestContext.request = req;
        req.requestBody = Blob.valueOf(testJson);
        RestContext.response = res;
            system.debug('res.. '+res);
        //System.assertEquals(200, res.statusCode);
            
            
        GDMSWebServiceController obj = new GDMSWebServiceController();
        GDMSWebServiceController.routeToMailbox(con.id);
        GDMSWebServiceController.routeToMailbox(con1.id);   
            
    }
    }



It is giving System.NullPointerException: Attempt to de-reference a null object error for line req.setEndpoint(setting.MuleUploadEndpoint__c);

Please suggest how can i resolved this issue.

Thanks,
A
Santiago CurettiSantiago Curetti
Hi Anish,

MuleEndpoint__c is a custom setting right, So you'll need to create that record in the test class.

Here is the objtecs that you have acces from test without creating them.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_data_access.htm

Insted of Custom setting I suggest to use Named Credentials to save the enpoint.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_named_credentials.htm

For test callouts, you need to set a Mock response.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm