0

enter image description hereTrigger

trigger UpdateRecordEventTrigger on dicecloud__UpdateRecord__e (after insert) { String recordId; List documentIdList = New List();

for(UpdateRecord__e thisUpdateRecord : Trigger.New){ 
    recordId = thisUpdateRecord.RecordId__c;
    documentIdList.addAll(thisUpdateRecord.DocumentIds__c.split(','));
}

if(!String.isBlank(recordId) && !documentIdList.isEmpty()){
    HTTPServiceController.sendDocumentWebService(
        recordId, 
        documentIdList
    );
}  

}

Class for handling future method. public class HTTPServiceController {

public static String boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';

@future (callout=true)
public static void sendDocumentWebService(String relatedRecordId, List<Id> documentIdList){
    String sentDocumentIds = '';
    Integer count = 0;
    try{           
        Map<Id, String>  fileBodyMap  = New Map<Id, String>();
        List<DICEDocumentDetail__c> documentDetailList = DocumentDetailHandler.getDocumentDetails(relatedRecordId);
        
        for(ContentVersion thisContentVersion : DocumentDetailHandler.getContentVersion(New Set<Id>(documentIdList))){
                
                Http httpRequest = new Http();
                  HttpRequest request = new HttpRequest();
                  request.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
                  request.setHeader('Accept','application/json');
                  request.setMethod('POST');
                  request.setEndpoint(url);  
                  request.setBodyAsBlob(
                    getFile(thisContentVersion.VersionData, 
                            thisContentVersion.ContentDocument.title +'.'+ 
                            thisContentVersion.ContentDocument.FileExtension
                           ));
                  request.setTimeout(60000);
               
                 HTTPResponse response = httpRequest.send(request);
               
                count++;
                if(response.getStatusCode() == 200){
                    sentDocumentIds   = sentDocumentIds + thisContentVersion.ContentDocumentId+',';
                    fileBodyMap.put(thisContentVersion.ContentDocumentId, response.getBody());
                }
        }
   
    }catch(Exception e) {
     
    } 
}

}

Test Class

@isTest private class UpdateRecordEventTrigger_Test {

@isTest
private static void firstMethod() {
   
    Opportunity thisOpportunity = TestObjectFactory.createOpportunity();
    INSERT thisOpportunity;
    
    DICEDocumentDetail__c thisDocumentDetail = TestObjectFactory.createDocumentDetail();
    thisDocumentDetail.RelatedRecordID__c = thisOpportunity.Id;
    INSERT thisDocumentDetail;
    
    ContentVersion thisContentVersion = New ContentVersion(); 
    thisContentVersion.Title='Header_Picture1'; 
    thisContentVersion.PathOnClient='/' + thisContentVersion.Title + '.jpg'; 
    thisContentVersion.VersionData=EncodingUtil.base64Decode('JVBERi0xLjQKJeLjz9MKNiAwIG9iago8PAovVHlwZSAvRXh0R1N0YXRlCi9TTSAwLjAyCi9TTWFzayAvTm9uZQovQUlTIGZhbHNlCi9TQSB0cnVlCi9jYSAxCi9DQSAxCj4+CmVuZG9iagoxMCAwIG9iago8PAovTGVuZ3RoMSAxMTU3MgovRmlsdGVyIC9GbGF0ZURlY29kZQovTGVuZ3RoIDY3OTgKPj4Kc3RyZWFtCnictVoJVFvXmX5XK5ZtDGYHA08IEIsAIQmJxWxCgNhldjBgCyQhYSGBJLDAdoJtrEkcT0LcLI6buE6aydpm2py048nJtE6ak3HTTKbHp+O0PW7qUtdN05xM2mmnHdd6zH/vexICO+4yZ+Qj3nv33Xv//f/+/8oUoigqilqi+BTV1VOiuvlP//NzGDkF3/5J54ItqD8xCffXKSrjmN1qtlgeby2hqEw7jGntMBB9POpReD4Pz9n2aZ//o29fG4fnt+H5d07'); 
    thisContentVersion.origin = 'H';
    INSERT thisContentVersion;
    
    ContentDocumentLink thisContentDocumentLink = New ContentDocumentLink();
    thisContentDocumentLink.LinkedEntityId    = thisOpportunity.Id;
    thisContentDocumentLink.contentdocumentid = [SELECT ContentdocumentId FROM contentversion 
                                                 WHERE Id =: thisContentVersion.Id].ContentdocumentId;
    thisContentDocumentLink.ShareType         = 'I';
    thisContentDocumentLink.Visibility        = 'AllUsers'; 
    INSERT thisContentDocumentLink;
    
    Test.startTest();
      Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
    
    //Publishing the Event
    UpdateRecord__e updateEvent = new UpdateRecord__e();
    updateEvent.IsTriggerCall__c = true;
    updateEvent.DocumentIds__c   = thisContentDocumentLink.ContentdocumentId;
    updateEvent.RecordId__c      = thisOpportunity.Id;
    EventBus.publish(updateEvent);
  
    Test.stopTest();
}

Mock class

@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    public final static String FAKE_RESPONSE = '{ "user_params": "","error": null, "time": 5.09,"fields": [ { "value": "00000033170007959", "key": "acc_no"}, { "value": "SBIN0000379","key": "ifsc"  },{ "value": "State Bank Of India","key": "bank_logo" },   {"value": "14","key": "bank_id"}],"tag": 37,"document_type": "Bank Statement"}';
    private static String boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
    global HTTPResponse respond(HTTPRequest req) {
        System.assertEquals('http://example.com/example/test', req.getEndpoint());
        System.assertEquals('POST', req.getMethod());
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBodyAsBlob(blob.valueOf(FAKE_RESPONSE));
        res.setStatusCode(200);
        return res;
    } 
}
0

Since the coverage stops at the line where you make the callout, you must be encountering an exception.

You have an empty catch block, and you're catching (and then swallowing) all exceptions. That's bad practice. It makes debugging harder, and it makes tests that should be failing pass instead. When working with async code you want more notification about issues, not less.

I suspect the issue is the first assertion you have in your mock callout, System.assertEquals('http://example.com/example/test', req.getEndpoint());

You should

  • Remove the pointless (and actively harmful) try/catch from HTTPServiceController
  • Ensure that the request url set in HTTPServiceController and the url you're asserting against in your mock callout class are the same
    • Or remove that assertion
    • Or change HTTPServiceController so you can inject the callout url (like, say, another static variable that you could then set/update in a unit test)
2
  • I have found the issue: CalloutException: System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out – Lokesh Malviya Feb 13 at 3:36
  • Any help will appreciated – Lokesh Malviya Feb 13 at 9:53

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.