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
Sharu PriyaSharu Priya 

How to write test class for rest api Class

Hi,

I m new to coding , Please help me on how to write Test class for code coverage for the below Rest api class
 
global class ZyncAPI {
    public CarePlanWrapper getZyncData() {
        // Instantiate a new http object        
        Http h = new Http();        
        // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint        
        HttpRequest req = new HttpRequest(); 
        String endUrl = 'http://carrotcube-esb-zynx.cloudhub.io/zynx/PlanDefinition';
        req.setEndpoint(endUrl);
        system.debug(endUrl);   
        req.setMethod('GET');        
        // Send the request, and return a response        
        HttpResponse res = h.send(req);
        system.debug(res.getBody());
        //List<HealthCloudGA__EhrCondition__c> patientCondition = new List<HealthCloudGA__EhrCondition__c>();
        //HealthCloudGA__EhrCondition__c Ehrpatientcondition;                               
        
        //ZyncJSONWrapper zyncresponse = new ZyncJSONWrapper();
        //List<ZyncJSONWrapper> zyncresponseData = new List<ZyncJSONWrapper>();
        //I tried the below one and zyncresponse.Action also still the same. 
        CarePlanWrapper PlanWrapper = new CarePlanWrapper();
        PlanWrapper = CarePlanWrapper.parse(res.getbody());
        system.debug(PlanWrapper);
        
        Map<string,List<HealthCloudGA__CarePlanGoal__c>> ProblemGoalMap = new Map<string,List<HealthCloudGA__CarePlanGoal__c>>();
        Map<string,List<Interventions__c>> GoalIntervensionMap = new Map<string,List<Interventions__c>>();
        Map<string,List<Task>> IntervensionTaskMap = new Map<string,List<Task>>();
        
        
        List<HealthCloudGA__CarePlanProblem__c> patientProblem = new List<HealthCloudGA__CarePlanProblem__c>();
        
        
        
        for(CarePlanWrapper.cls_entry entry : PlanWrapper.entry){
            List<HealthCloudGA__CarePlanGoal__c> GoalsList = new List<HealthCloudGA__CarePlanGoal__c>();
            for(CarePlanWrapper.cls_action actionRec : entry.resource.action){
                HealthCloudGA__CarePlanGoal__c cpgoal = new HealthCloudGA__CarePlanGoal__c();
                cpgoal.Name = actionRec.Title;
                GoalsList.add(cpGoal);
                List<Interventions__c> intervensionList = new List<Interventions__c>();
                for(CarePlanWrapper.cls_action goal : actionRec.action){
                    Interventions__c intervension = new Interventions__c();
                    if(goal.title != Null && goal.title.length() > 80)
                        intervension.Name = goal.Title.substring(0,80);
                    else
                        intervension.Name = goal.Title;
                    intervension.Title__c = goal.Title;
                    intervensionList.add(Intervension);
                    if(goal.action != Null){
                        List<task> taskList = new List<Task>();
                        for(CarePlanWrapper.Cls_Action task : goal.action){
                            task tsk = new Task();
                            tsk.Subject = task.title;
                            tsk.priority = 'Medium';
                            tsk.status = 'Not started';
                            taskList.add(tsk);
                        }
                        IntervensionTaskMap.put(entry.Resource.Title+actionRec.Title+goal.Title,TaskList);
                    }
                }                
                GoalIntervensionMap.put(entry.Resource.Title+actionRec.Title,intervensionList);
            }
            HealthCloudGA__CarePlanProblem__c cpproblem = new HealthCloudGA__CarePlanProblem__c();
            cpproblem.Name = entry.Resource.Title;
            patientProblem.add(cpproblem);
            ProblemGoalMap.put(entry.Resource.Title,GoalsList);
        }
        system.debug(ProblemGoalMap);
        system.debug(GoalIntervensionMap);
        System.debug(IntervensionTaskMap);
        
        system.debug(ProblemGoalMap.KeySet().size());
        system.debug(GoalIntervensionMap.Keyset().size());
        system.debug(IntervensionTaskMap.keyset().size());
        
        
        
        Map<string,string> ProblemIdMap = new Map<string,string>();
        Map<string,string> GoalIdMap = new Map<string,string>();
        List<HealthCloudGA__CarePlanGoal__c> GoalUpdateList = new List<HealthCloudGA__CarePlanGoal__c>();
        
        if(patientProblem.size() > 0)
            upsert patientProblem;
        
        for(HealthCloudGA__CarePlanProblem__c Problem : patientProblem){
            ProblemIdMap.put(problem.Name,Problem.id);
        }    
            
        for(string Plan : ProblemGoalMap.Keyset()){
            for(HealthCloudGA__CarePlanGoal__c goal : ProblemGoalMap.get(plan)){
                goal.HealthCloudGA__CarePlanProblem__c = ProblemIdMap.get(plan);
                GoalUpdateList.add(goal);
            }
        }
        
        if(GoalUpdateList.size() > 0)
            upsert GoalUpdateList;
        
        for(HealthCloudGA__CarePlanGoal__c goal : [select id,name,HealthCloudGA__CarePlanProblem__r.Name from HealthCloudGA__CarePlanGoal__c where id IN: GoalUpdateList]){
            GoalIdMap.put(goal.HealthCloudGA__CarePlanProblem__r.Name+goal.Name,goal.id);
        }
        
        List<Interventions__c> InterventionUpdateList = new List<Interventions__c>();
        for(string intervension : GoalIntervensionMap.Keyset()){
            for(Interventions__c inter : GoalIntervensionMap.get(intervension)){
                inter.Goal__c = GoalIdMap.get(intervension);
                InterventionUpdateList.add(inter);
            }
        }
        
        if(InterventionUpdateList.size() > 0)
            upsert InterventionUpdateList;
        Map<string,string> IntervesionIdMap = new Map<string,string>();
        for(Interventions__c inter : [select id,Title__c,Goal__r.Name,Goal__r.HealthCloudGA__CarePlanProblem__r.Name from Interventions__c where id in: InterventionUpdateList]){
            IntervesionIdMap.put(inter.Goal__r.HealthCloudGA__CarePlanProblem__r.Name+inter.goal__r.name+inter.Title__c,inter.id);
        }  
        
        system.debug(IntervesionIdMap.Keyset());
        system.debug(IntervensionTaskMap.keySet());
        
        for(string s : IntervesionIdMap.Keyset()){
            system.debug(s);
        }
        
        List<task> TaskUpdateList = new List<task>();
        for(string taskString : IntervensionTaskMap.keySet()){
            for(Task tsk : IntervensionTaskMap.get(taskString)){
                tsk.whatId = IntervesionIdMap.get(taskString);
                TaskUpdateList.add(tsk);
            }
        }  
        
        system.debug(TaskUpdateList[0]);

        if(TaskUpdateList.size() > 0)
            Upsert TaskUpdateList;

       try{
            if(res.getStatusCode() == 200)
            {
              
            }
        }
        catch(exception e){}
        return PlanWrapper;
  }
}

Thank You,
Sharu​
Rahul KumarRahul Kumar (Salesforce Developers) 
Hi
Please check below post to how to write test class for Rest API
1http://amitsalesforce.blogspot.com/2016/04/rest-api-in-salesforce-execute-rest-api.html (http:// http://amitsalesforce.blogspot.com/2016/04/rest-api-in-salesforce-execute-rest-api.html)
2) http://salesforce.stackexchange.com/questions/4988/writing-test-classes-for-apex-restservice
3) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm (http:// https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm)

For best practice please check below post
1) http://amitsalesforce.blogspot.com/2015/06/best-practice-for-test-classes-sample.html
Please follow below Salesforce Best Practice for Test Classes:-

1. Test class must start with @isTest annotation if class version is more than 25
2. Test environment support @testVisible , @testSetUp as well
3. A unit test is to test a particular piece of code working properly or not.
4. Unit test method takes no argument, commit no data to the database, send no email, flagged with the testMethod keyword.
5. To deploy to production at least 75% code coverage is required
6. System.debug statement are not counted as a part of apex code limit.
7. Test method and test classes are not counted as a part of code limit
9. We should not focus on the percentage of code coverage, we should make sure that every use case should be covered including positive, negative, record .bulk and record.
Single Action -To verify that the single record produces the correct an expected result.
Bulk action -Any apex record trigger, class or extension must be invoked for 1-200 records.
Positive behavior: Test every expected behavior occurs through every expected permutation, i,e user filled out every correct data and not go past the limit.
Negative Testcase: -Not to add future date, Not to specify the negative amount.
Restricted User: -Test whether a user with restricted access used in your code.
10. Test class should be annotated with @isTest.
11 . @isTest annotation with test method is equivalent to the testMethod keyword.
12. Test method should static and no void return type .
13. Test class and method default access are private, no matter to add access specifier.
14. classes with @isTest annotation can't be an interface or enum.
15. Test method code can't be invoked by non-test request.
16. Starting with Salesforce API 28.0 test method can not reside inside non-test classes.
17. @Testvisible annotation to make visible private methods inside test classes.
18. The test method can not be used to test web-service call out . Please use call out mock.
19. You can't  send email from the test method.
20.User, profile, organization, AsyncApexjob, Cron trigger, RecordType, ApexClass, ApexComponent ,ApexPage we can access without (seeAllData=true) .
21. SeeAllData=true will not work for API 23 version earlier.
22. Accessing static resource test records in test class e,g List<Account> accList=Test.loadData(Account,SobjectType,'ResourceName').
23. Create TestFactory class with a @isTest annotation to exclude from organization code size limit.
24. @testSetup to create test records once in a method and use in every test method in the test class.
25. We can run a unit test by using Salesforce Standard UI,Force.com IDE, Console, API.
26. A maximum number of test classes run per 24 hours of the period is not greater of 500 or 10 multiplication of test classes of your organization.
27. As apex runs in system mode so the permission and record sharing is not taken into account. So we need to use the system.runAs to enforce record sharing.
28. System.runAs will not enforce user permission or field level permission.
29. Every test to runAs count against the total number of DML issued in the process.

Please mark it as best answer if the information is informative.

Best Regards
Rahul Kumar