+ Start a Discussion
rajubalajirajubalaji 

what to write a test class for the apex class which @httppost?

Hi Everyone,

I was new to write a apex test class.please find the below code and help me how to write a test class for that and if possible please explain me line by line it well really helpful for me.Thanks inadvance.

@RestResource(urlMapping='/DeleteInfo/*')
global class DeleteInfo {
@HttpPost
    global static String doPost() {
        String responseJSON;
        if (RestContext.request.requestBody != null) {
            String requestStatus;
            String reqBody = RestContext.request.requestBody.toString();
            String parentId = null;
            Request Request = new Request();
            String environmentCode = Utility.getEnvironmentCode(UserInfo.getUserName());
            
            try {
                Req req = (Req)JSON.deserialize(reqBody, DeleteInfo.Req.class);
                Request = req.Request;
                
                if (Request.parent != null) {
                    if (Request.parent.StarID != null && Request.parent.StarID != '') {
                        String parentStarID = Request.parent.StarID + '__' + environmentCode;
                        List<Hub_Parent__c> ptList = [select Id from Hub_Parent__c where StarIDt__c = :parentStarID Limit 1];
                        
                        if (ptList.size() > 0) {
                            Hub_Parent__c objparent = ptList[0];
                            parentId = objparent.Id;
                            
                            DataDelete.DataDelete(objParent.Id);
                            
                            responseJSON = InboundTransactionResponse.GetSucessResponse(Request.Header.TransactionType, Request.Header.TimeStamp, Request.Header.FileID, Request.parent.StarID);
                            requestStatus = 'Success';
                        }
                        else {
                            responseJSON = InboundTransactionResponse.GetErrorResponse(Request.Header.TransactionType, Request.Header.TimeStamp, Request.Header.FileID, Request.parent.StarID, 'StarID', '0056', 'StarID doesn\'t exists in system');
                            requestStatus = 'Failure';
                        }
                    }
                    else {
                        responseJSON = InboundTransactionResponse.GetErrorResponse(Request.Header.TransactionType, Request.Header.TimeStamp, Request.Header.FileID, null, 'StarID', '001', 'StarID is a required field.');
                        requestStatus = 'Failure';
                    }
                }
                else {
                    responseJSON = InboundTransactionResponse.GetErrorResponse(Request.Header.TransactionType, Request.Header.TimeStamp, Request.Header.FileID, null, 'parent', '001', 'Invalid request format.');
                    requestStatus = 'Failure';
                }
                BlueStarTransactionDetails.CreateInboundTransactionRequest(Request.Header.TransactionType, Request.Header.FileID, requestStatus, reqBody, responseJSON, null, null, null, environmentCode);
            }
            catch (Exception ex) {
                System.debug('Delete Exception: ' + ex.getMessage());
                String fileId;
                if (Request.Header != null && Request.Header.FileID != null) {
                    fileId = Request.Header.FileID;
                }
                else {
                    fileId = 'Unknown';
                }
                BlueStarTransactionDetails.CreateInboundTransactionRequest(Request.Header.TransactionType, fileId, 'Exception', reqBody, ex.getMessage(), null, null, null, environmentCode);
                if(Request != null && Request.Header != null){
                  responseJSON = InboundTransactionResponse.GetErrorResponse(Request.Header.TransactionType, Request.Header.TimeStamp, Request.Header.FileID, null, 'Error', '0056', ex.getMessage());
                }else{
                    responseJSON = ex.getMessage();
                }
            }
        }
        return responseJSON;
    }
    
    public class parent {
        public String StarID {get;set;}
    }
    
    public class Header {
        public String TransactionType {get;set;}
        public String TimeStamp {get;set;}
        public String FileID {get;set;}
    }
    
    public class Request {
        public parent parent {get;set;}
        public Header Header {get;set;}
    }
    
    public class Req {
        public Request Request {get;set;}
    }
}

Thanks inadvance.
AbhishekAbhishek (Salesforce Developers) 
Hi,

The below blogs which might answer your query,

https://developer.salesforce.com/forums/?id=9060G000000XdDoQAK

https://developer.salesforce.com/forums/?id=906F0000000MLciIAG

I hope you find the above information is helpful. If it does, please mark as Best Answer to help others too.

Thanks.
rajubalajirajubalaji
Hi Abhishek,

Thank you so much for very quick reply..by your help i have done written test class but i have not done complete 75% code coverage.please help me to improve the code coverage.

@isTest
public class DeleteInfo_Test {
    static testMethod Void Test(){
        Test.startTest();
        
        HubTestController.createCustomSettings();
        HubTestController.createEnviornmentSettingsWithUserName(UserInfo.getUserName());
        Hub_Parent__c pt = HubTestController.getMockParentObject();        
        
        Hub_Parent__c Testpt = new Hub_Parent__c();
        
        String TransactionType = 'DeletePatientInfo';
        String transactionId = StarTransactionDetails.CreateInitialOutboundTransactionRequestForAccount(TransactionType, pt.AccountID__c, pt.Enviornment_Code__c);
        TransactionDetail__c tran = [select Id, FileID__c from TransactionDetail__c where ID = :transactionId];
        
        String responseBody  = '{"Response":{"Header":{"TransactionType":"DeleteInfo","TimeStamp":"12-16-2016 15:12:48:224","FileID":"DeletePatientInfo.a0fP0000002cYyMIAU","Status":"Success"},"ResponseType":{"StarID":"W0000010726","FailedUsers":null}}}';
        
        RestRequest req = new RestRequest();
        req.httpMethod = 'POST';
        RestContext.request = req;
        
        RestResponse res = new RestResponse();
        RestContext.response = res;
        
        //String str = '{\"Response\":{\"ResponseType\":{\"StarID\":\"' + pt.StarID__c.replace('__bst','') + '\"},\"Header\":{\"TransactionType\":\"DeleteInfo\",\"TimeStamp\":\"10-24-2019 08:54:52:972\",\"Status\":\"Success\",\"FileID\":\"DeleteInfo.SDvk1zce4m4k\"}}}';
        String str = '{\"Request\":{\"Header\":{\"TransactionType\":\"DeleteInfo\",\"TimeStamp\":\"10-24-2019 08:54:52:972\",\"FileID\":\"DeleteInfo.SDvk1zce4m4k\"},\"Subscription\":{\"StarID\":\"' + pt.StarID__c.replace('__bst','') + '\",\"AddressLine1\":\"3301 S Greenfield Rd\",\"City\":\"Gilbert\",\"State\":\"AZ\",\"Country\":\"United States\",\"ZipCode\":\"85297\",\"TestStripsFrequency\":\"2 times/day\",\"Status\":\"Final\",\"NextShipmentDate\":\"2019-10-26\"}}}';
        RestContext.request.requestBody = Blob.valueOf(str);
        DeleteInfo.doPost();
        
        Test.stopTest();
    }
    
}

please help me to know the more..

thanks inadvance.