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
rajubalajirajubalaji 

how to develop test class for web service httppost

Hello everyone,

i'm developing a webservice in rest and i have no idea about how write a test class in this case and this is my code.Please anyone help.

@RestResource(urlMapping='/BulkPatientDeactivationResponse/*')
global class BulkPatientDeactivationResponse {
    @HttpPost
    global static void doPost() {
        if (RestContext.request.requestBody != null) {
            Savepoint sp = Database.setSavepoint();
            try {
                String environmentCode = Utility.getEnvironmentCode(UserInfo.getUserName());
                
                String reqBody = RestContext.request.requestBody.toString();
                if (reqBody.contains('Header')) {
                    TranRes res = (TranRes)JSON.deserialize(reqBody, BulkPatientDeactivationResponse.TranRes.class);
                    String fileName = 'Unknown', type = 'Unknown', status = 'Unknown';
                    if (res.Response.Header.FileID != null) {
                        fileName = res.Response.Header.FileID;
                    }
                    if (res.Response.Header.TransactionType != null) {
                        type = res.Response.Header.TransactionType;
                    }
                    if (res.Response.Header.Status != null) {
                        status = res.Response.Header.Status;
                    }
                    List<TransactionDetail__c> tranList = [select Id, Transaction_Status__c, Response_JSON__c, HUB_Practice__c, HUB_Provider__c, Comments__c, Request_JSON__c from TransactionDetail__c where FileID__c = :fileName and Name = :type Limit 1];
                    
                    if (res.Response.ResponseType.AccountCode != null && res.Response.ResponseType.AccountCode != '') {
                        List<Account> lstAccount = [Select Id, Model_Number__c from Account where BluestarId__c =: res.Response.ResponseType.AccountCode and Enviornment_Code__c = :environmentCode Limit 1];
                        if (lstAccount.size() > 0) {
                            TransactionDetail__c transDetail = tranList.get(0);
                            BulkPatientDeactivationController.BulkPatientDeactivation bulkPatientDeactivationUser = (BulkPatientDeactivationController.BulkPatientDeactivation)JSON.deserialize(transDetail.Request_JSON__c, BulkPatientDeactivationController.BulkPatientDeactivation.class);
                            
                            if (res.Response.ResponseType.SuccessUsers != null && res.Response.ResponseType.SuccessUsers != '') {
                                Attachment file = new Attachment();
                                file.name = bulkPatientDeactivationUser.Request.Patient.Data + '-SuccessBulkDeactivationUsers' + '.json';
                                file.parentId = lstAccount[0].Id;
                                file.body = Blob.valueOf(res.Response.ResponseType.SuccessUsers);
                                insert file;
                                
                                String successUsersContent = '{"User":' + res.Response.ResponseType.SuccessUsers + '}';
                                Users successUsers = (Users)JSON.deserialize(successUsersContent, BulkPatientDeactivationResponse.Users.class);
                                Integer userCount = successUsers.User.size();
                                
                                List<String> lstBlueStarIDs = new List<String>();
                                for (Integer i = 0; i < userCount; i++) {
                                    lstBlueStarIDs.Add(successUsers.User[i].BlueStarID + '__' + environmentCode);
                                }
                                
                                List<Hub_Patient__c> lstPatients = [select Id, BlueStarID__c from Hub_Patient__c where BlueStarID__c in :lstBlueStarIDs];
                                
                                List<Hub_Patient__c> lstPatientsToDeactivate = new List<Hub_Patient__c>();
                                List<Id> deactivationPatients = new List<Id>();
                                for (Hub_Patient__c usr:lstPatients){
                                    deactivationPatients.Add(usr.Id);
                                    
                                    //Update Patient Status
                                    usr.Product_Status__c = 'Inactive';
                                    usr.ProductStatusReason__c = bulkPatientDeactivationUser.Request.Patient.DeactivateReason;
                                    usr.Status__c = Label.HubStat_Inactive;
                                    lstPatientsToDeactivate.Add(usr);
                                }
                                                                
                                //CheckAndCloseAllTaskForPatients
                                List<Task> lstTask = [select Id, Type, Status from Task where WhatId in :deactivationPatients and Type != :Label.TaskType_PatientDrivenFailure and Status != 'Closed'];
                                if (lstTask.size() > 0) {
                                    for (Integer j = 0; j < lstTask.size(); j++) {
                                        lstTask[j].Status = 'Closed';
                                    }
                                    update lstTask;
                                }
                                
                                List<TransactionDetail__c> lstTran = new List<TransactionDetail__c>();
                                if (lstPatientsToDeactivate.size() > 0) {
                                    List<Database.SaveResult> lstResult = Database.update(lstPatientsToDeactivate, false);
                                    for (Integer i = 0; i < lstResult.size(); i++) {
                                        if (!lstResult[i].isSuccess()) {
                                            String message = null;
                                            Database.Error[] errs = lstResult[i].getErrors();
                                            for (Integer j = 0; j < errs.size(); j++){
                                                message = message + '\\n' + errs[j].getStatusCode() + ': ' + errs[j].getMessage() + '.'; 
                                            }
                                            TransactionDetail__c tran = new TransactionDetail__c();
                                            tran.Name = 'BulkPatientDeactivationFailure';
                                            tran.Transaction_Type__c = 'Inbound';
                                            tran.Transaction_Status__c = 'Exception';
                                            tran.Account__c = lstAccount[0].Id;
                                            tran.Request_JSON__c = JSON.serialize(successUsers.User[i]);
                                            tran.Response_JSON__c = message;
                                            lstTran.add(tran);
                                        }
                                    }
                                }
                                if (lstTran.size() > 0) {
                                    Database.insert(lstTran, false);
                                }
                            }
                            
                            if (res.Response.ResponseType.FailureUsers != null && res.Response.ResponseType.FailureUsers != '') {
                                Attachment file = new Attachment();
                                file.name = bulkPatientDeactivationUser.Request.Patient.Data + '-FailureBulkDeactivationUsers' + '.json';
                                file.parentId = lstAccount[0].Id;
                                file.body = Blob.valueOf(res.Response.ResponseType.FailureUsers);
                                insert file;
                                
                                TransactionDetail__c tran = new TransactionDetail__c();
                                tran.Name = 'BulkPatientDeactivationFailure';
                                tran.Transaction_Type__c = 'Inbound';
                                tran.Transaction_Status__c = 'Exception';
                                tran.Account__c = lstAccount[0].Id;
                                tran.Request_JSON__c = 'Error Deactivating Users in product. Error Deactivation Users details : ' + res.Response.ResponseType.FailureUsers;
                                tran.Response_JSON__c = 'Error Deactivating Users in product.';
                                Database.insert(tran);
                            }
                        }
                    }
                    
                    if (tranList.size() > 0) {
                        TransactionDetail__c tran = tranList[0];
                        tran.Transaction_Status__c = status;
                        tran.Response_JSON__c = reqBody;
                        update tran;
                    }
                    else {
                        BlueStarTransactionDetails.CreateUnknownTransactionResponse(fileName, status, reqBody);
                    }
                }
                else if (reqBody.contains('SchemaError')) {
                    SchemaErrorTran schemaErr = (SchemaErrorTran)JSON.deserialize(reqBody, BulkPatientDeactivationResponse.SchemaErrorTran.class);
                    System.debug(schemaErr);
                    if (schemaErr.Response.SchemaError.FileName != null) {
                        String fileName = schemaErr.Response.SchemaError.FileName.replace('SD_WD_', '').replace('_', '.').replace('.xml', '');
                        String tranStatus = 'Failure: ';
                        if (schemaErr.Response.SchemaError.ErrorText != null) {
                            if (schemaErr.Response.SchemaError.ErrorText.length() > 23) {
                                tranStatus = tranStatus + schemaErr.Response.SchemaError.ErrorText.substring(0, 22);
                            }
                            else {
                                tranStatus = tranStatus + schemaErr.Response.SchemaError.ErrorText;
                            }
                        }
                        List<TransactionDetail__c> tranList = [select Id, Transaction_Status__c, Response_JSON__c from TransactionDetail__c where FileID__c = :fileName Limit 1];
                        if (tranList.size() > 0) {
                            TransactionDetail__c tran = tranList[0];
                            tran.Transaction_Status__c = tranStatus;
                            tran.Response_JSON__c = reqBody;
                            update tran;
                        }
                        else {
                            BlueStarTransactionDetails.CreateUnknownTransactionResponse(schemaErr.Response.SchemaError.FileName, tranStatus, reqBody);
                        }
                    }
                    else {
                        BlueStarTransactionDetails.CreateUnknownTransactionResponse('Unknown', 'Unknown', reqBody);
                    }
                }
                else {
                    BlueStarTransactionDetails.CreateUnknownTransactionResponse('Unknown', 'Unknown', reqBody);
                }
            } catch (Exception ex) {
                Database.rollback(sp);
                String resp = RestContext.request.requestBody.toString();
                BlueStarTransactionDetails.CreateErrorProcessingTransactionResponse('Unknown', 'Exception', resp, ex.getMessage());
            }
        }
    }
    
    public class TranHeader {
        public String TransactionType;
        public String TimeStamp;
        public String FileID;
        public String Status;
    }
    
    public class ResType {
        public String HubCode {get;set;}
        public String BlueStarID {get;set;}
        public String AccountCode {get;set;}
        public String SuccessUsers {get;set;}
        public String FailureUsers {get;set;}
        public String FailedUsers {get;set;}
    }
    
    public class TranResp {
        public TranHeader Header;
        public ResType ResponseType;
    }
    
    public class TranRes {
        public TranResp Response;
    }
    
    public class SchemaErr {
        public String FileName {get;Set;}
        public String ErrorText {get;set;}
    }
    
    public class SchemaErrorResp {
        public SchemaErr SchemaError;
    }
    
    public class SchemaErrorTran {
        public SchemaErrorResp Response;
    }
    
    public class Users {
        List<DeactivationUser> User {get;set;}
    }
    
    public Class DeactivationUser {
        String Email {get;set;}
        String BlueStarID {get;set;}
    }
}

Please any one help me.

Thanks Inadvance
ManojjenaManojjena
HI Balaji ,

Please check this link below and try to do and let us know incase any issue .

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

Thanks ,
Manoj
rajubalajirajubalaji
Hi Manojjena,

Thanks for support but i already tried with that code but i will not reach the coverage.So can you please help me.

Thanks in Advance.
ManojjenaManojjena
HI Balaji,

How much coverage you are getting now ,where do u find difficulty . I think after this it will be normal test class .

Thanks ,
Manoj