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
Raja.PRaja.P 

need help in Writing a test class ......

Hii Friends

I am not familiar  at writing test clas i got arequirement 
so please kindly  help me in writing this test class 


Thanks in advance 



public class EF_Updateabc
{
    public EF_Updateabc()
    {
        UpdateEFKotaQueue();
    }
    public void UpdateEFKotaQueue()
    {
        List<string> lstEF_abc_QueueID = new List<string>();
        /*string strQuery =  EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Type__c + ' ' + EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Fields__c +
                           EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Relationship_fields__c + ' from ' +  EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Object__c +
                           ' where ' + EF_SOQL_Statements__c.getValues('EF_abc_Queue_Batch_Query').Filter__c;
        system.debug('strQuery strQuery strQuery ::' + strQuery );
        List <EF_abc_Queue__c> lstEFabc_Queue_QueryData = Database.Query(strQuery);*/
      
        List <EF_abc_Queue__c> lstEFabc_Queue_QueryData = [SELECT Id, status__c, EF_Requested_Resource__c, abc_JSON__c,abc_Response__c, number_tried__c, EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c, EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c, EF_Requested_Resource__r.Request_Type__c from EF_abc_Queue__c where status__c='Request Sent' and number_tried__c<10 limit 10];
        system.debug('lstEFabc_Queue_QueryDatalstEFabc_Queue_QueryData::' + lstEFabc_Queue_QueryData);
       
        for(EF_abc_Queue__c objEF_abc_Queue_Local : lstEFabc_Queue_QueryData)
        {
            lstEF_abc_QueueID.add(objEF_abc_Queue_Local.Id);
        }
      
        if(lstEF_abc_QueueID.size()>0)
        {
            list<EF_abc_Queue__c> lstEfabctoUpdate = new list<EF_abc_Queue__c>();
            for(EF_abc_Queue__c oQueue: [select id, EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c,
                            EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c,
                            abc_JSON__c, number_tried__c, EF_Requested_Resource__r.Request_Type__c,
                            EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c, Status__c
                            from EF_abc_Queue__c
                            where id in : lstEF_abc_QueueID])
            {
                string userID = oQueue.EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c!=''?
                                oQueue.EF_Requested_Resource__r.EF_Request_ID__r.abc_Id__c:oQueue.EF_Requested_Resource__r.EF_Request_ID__r.User_Name__r.abc_Id__c;

                string appID = oQueue.EF_Requested_Resource__r.EF_Resource_Metadata__r.abc_App_ID__c;
              
                string strURLEnd = abc_EndPoint__c.getValues('abc').Site_URL__c;
                strURLEnd = strURLEnd + '/apps/' + appID + '/users/' + userID;
              
                String result     = '[]';
                String authToken    = abc_EndPoint__c.getValues('abc').Auth_token__c;
                Http h = new Http();
                HttpRequest req   = new HttpRequest();
                req.setEndpoint(strURLEnd);
                req.setMethod('GET');
                req.setHeader('Accept', 'application/json');
                req.setHeader('Authorization', authToken);
              
                HttpResponse res = h.send(req);
              
                if (200 == res.getStatusCode())
                {
                    result = res.getBody();
                    map<string, Object> mapDataToUpdate = (map<string, Object>)JSON.deserializeUntyped(result);
                  
                    if(mapDataToUpdate.get('status') == 'Completed')
                    {
                        oQueue.Status__c = 'Complete';
                        lstEfabctoUpdate.add(oQueue);
                    }
                }
            }
          
            if(lstEfabctoUpdate.size()>0)
            {
                try{update lstEfabctoUpdate;}
                catch(Exception ex){EF_Error_Log.logException('EF_abc_Queue', lstEfabctoUpdate, 'DML', 'HIGH', ex.getMessage());
                }
            }
        }
    }
magicforce9magicforce9
Hi,

There are two approaches to test your class.
1. Is that you put an if condition before your HTTP callout and not make the call out in the test class...i.e by adding

if (!Test.isRunningTest()) {

               HttpResponse res = h.send(req);
                if (200 == res.getStatusCode())
                {
                    result = res.getBody();
                    map<string, Object> mapDataToUpdate = (map<string, Object>)JSON.deserializeUntyped(result);
                 
                    if(mapDataToUpdate.get('status') == 'Completed')
                    {
                        oQueue.Status__c = 'Complete';
                        lstEfabctoUpdate.add(oQueue);
                    }

}

2. Another is to create a mock response, Since you are doing a HTTP call out you'll need to create a MockHTTPResponse(aka Fake response) to test it. You'll need to create two test classes - One for MockResponse and one for actually testing the class. You can use the below code that I've provided for both of the classes(You might need to make some changes)....Hope it helps :-)

a. Test_EF_Updateabc.class //This is the mock http class
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
   
    // Implement the interface method
    global HTTPResponse respond(HTTPRequest req) {
       
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');

        /*You can either create a proper fake JSON response if you are not skipping
        the validation or if you put the if statement in your actual class to not go thru validation
        then just use an empty body...Eg: res.setBody('');  */
        res.setBody(getJSONBody());
        res.setStatusCode(200);
        return res;
    }

    global string getJSONBody()
    {
   
    //NOTE: You'll have to write your JSON string, the one one given below is just a sample
    String json = '{'+
  '\"kind\": \"youractualvalue#\",'+
  '\"etag\": \"\\\"jSwUP5mXUGwzAFbnLazODtWp_hU/xkmGPffByZklbXyXQDh4klvmhzo\\\"\",'+
  '\"pageInfo\": {'+
  '\"totalResults\": 1,'+
  '\"resultsPerPage\": 1'+
  '},'+
  '\"items\": ['+
  '{'+
  '\"kind\": \"channel#someChannel\",'+
  '\"etag\": \"\\\"jSwUP5mXUGwzAFbnLazODtWp_hU/YXgdzso7M5zhQmxu42URIvfh6VE\\\"\",'+
  '\"id\": \"UCapvR3azz2asadasdqdRGie0tng\",'+
  '\"statistics\": {'+
  '\"viewCount\": \"87896\",'+
  '\"commentCount\": \"8\",'+
  '\"subscriberCount\": \"657\",'+
  '\"hiddenSubscriberCount\": false,'+
  '\"videoCount\": \"93\"'+
  '}'+
  '}'+
  ']'+
  '}';
    return json;
    }
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

b. Test_EF_Updateabc.class //The Real test class
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
@isTest
private class Test_EF_Updateabc {


    //There are three A's(Arrange, Act, Assert) that you'll need to take care of in your test class

     static testMethod void testCallout() {
       
        /* Populate Test data, in your case in EF_abc_Queue__c object and other parent object where the data is being pulled up by the SOQL you
        have in actuall class satisfying the WHERE condition(where status__c='Request Sent' and number_tried__c<10)
        Also you need to populate data into the custom setting abc_EndPoint__c
        This is where you are arranging the test data
        */
        final User_Name__c user = new User_Name__c();
        //Populate data for rest of the fields
        insert user;
       
        EF_Request_ID__c request = new EF_Request_ID__c();
        request.User_Name__c = user.id;
        //Populate data for rest of the fields
        insert request;

        final EF_Requested_Resource__c resource = new EF_Requested_Resource__r();
        resource.EF_Request_ID__c = request.id;
        //Populate data for rest of the fields
        insert resource;

        final EF_abc_Queue__c queue = new EF_abc_Queue__c();
        queue.EF_Requested_Resource__c = resource.id;
        //Populate data for rest of the fields
        insert queue;

        final abc_EndPoint__c customSetting = new abc_EndPoint__c();
        //Populate data for the data set 'abc'
        insert customSetting;
       
  // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
       
        //Now its time for action, so lets initialise your actual class
        Test.startTest();
        EF_Updateabc testObj = new EF_Updateabc();
        Test.stopTest();
       
        //Now you can assert and see if the value actually got updated.
        EF_abc_Queue__c q = [Select Status__c from EF_abc_Queue__c where Id = :queue.id];
        System.assert(q.Status__c == 'Complete');
       
    }
}
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Raja.PRaja.P
Thanks for u r help i am still facing some issue in that