[SalesForce] Test Class for HTTP Callout getting Zero Code Coverage

I'm trying to write a test class for my HttpCallout. The code is working, but I'm having trouble with the test class. I've tried to use the MockHTTPResponse, but I'm still getting zero code coverage. The goal of the code is that when I click a button, that it will make the callout and parse the JSON response, and then display the response on the detail page in Salesforce. I've attached my Controller, Visualforce Page, and current Test Class below. Any help would be greatly appreciated! Thanks in advance!

While researching I saw this resource as well (page 394):
https://resources.docs.salesforce.com/sfdc/pdf/dbcom_apex_language_reference.pdf?major=178

Controller

 global class MicFire {
        Id thisRecId;
        Recommendation_Request__c recParams;
        public String recResponseBody { get; set; }    

        public MicFire(ApexPages.standardController sc){
            thisRecId = ApexPages.currentPage().getParameters().get('Id');
            recParams = [SELECT Rest_API_Parms__c FROM Recommendation_Request__c WHERE Id = :thisRecId];
        }

       global void basicAuthCallout(){

         HttpRequest req = new HttpRequest();

         req.setEndpoint('*my http Endpoint*' + recParams.REST_API_Parms__c);

         req.setMethod('GET');

         // Specify the required secretKey to access the endpoint
         // As well as the header and header information

         String secretKey = *my secret key*;

         String authorizationHeader = 'BASIC ' + secretKey; 

         req.setHeader('Authorization', authorizationHeader);

         // Create a new http object to send the request object
         // A response object is generated as a result of the request 

         Http http = new Http();

         HTTPResponse res = http.send(req);

         // Body of the Recommendation Response
         recResponseBody = res.getBody();

         System.debug(recResponseBody);


         Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(recResponseBody);

         // Parse the JSON for error response, and get either Error Description or Message of Invalid Key 
         Object errors = (Object)m.get('errorDescription');
         Object errorInvalidKey = (Object)m.get('Message');

         String errorsString = String.valueOf(errors);
         String errorInvalidKeyString = String.valueOf(errorInvalidKey);

         // List of Products for Ideals, IdealsFiltered, and InBudgets
         List<Object> ideals = (List<Object>)m.get('ideal');
         List<Object> idealsFiltered = (List<Object>)m.get('idealFiltered');
         List<Object> inBudgets = (List<Object>)m.get('InBudget');

         System.debug('++++++++++++++++++++++++++++++++++ Ideals List: ' + ideals);
         System.debug('++++++++++++++++++++++++++++++++++ IdealFiltered List: ' +idealsFiltered);
         System.debug('++++++++++++++++++++++++++++++++++ inBudgets List: ' + inBudgets);
         System.debug('++++++++++++++++++++++++++++++++++ errors: ' + errorsString);
         System.debug('++++++++++++++++++++++++++++++++++ error invalid key: ' + errorInvalidKeyString);

         // Recommendation Responses
         Recommendation_Response__c idealType = new Recommendation_Response__c(Rec_Response_Type__c = 'Ideal', Recommendation_Request__c = thisRecId);
         Recommendation_Response__c filteredType = new Recommendation_Response__c(Rec_Response_Type__c = 'Ideal Filtered', Recommendation_Request__c = thisRecId);
         Recommendation_Response__c inBudgetType = new Recommendation_Response__c(Rec_Response_Type__c = 'InBudget', Recommendation_Request__c = thisRecId);
         Recommendation_Response__c errorType = new Recommendation_Response__c(Rec_Response_Type__c = 'Error', Recommendation_Request__c = thisRecId, Recommendation_Response_Log__c = errorsString);
         Recommendation_Response__c errorInvalidKeyType = new Recommendation_Response__c(Rec_Response_Type__c = 'Error', Recommendation_Request__c = thisRecId, Recommendation_Response_Log__c = errorInvalidKeyString);

         // List of Recommendation Response Products for each Recommendation Response
         List<Recommendation_Response_Product__c> idealList = new List<Recommendation_Response_Product__c>();
         List<Recommendation_Response_Product__c> filteredIdealList = new List<Recommendation_Response_Product__c>();
         List<Recommendation_Response_Product__c> inBudgetList = new List<Recommendation_Response_Product__c>();

         // Find the Recommendation Engine pricebook
         Id recEngineBook = [SELECT Id FROM PriceBook2 WHERE Name = 'Recommendation Engine'].id;
         // Take all of the Pricebook Entries from that pricebook
         List<PriceBookEntry> productIdList = [SELECT p.Product2Id FROM PricebookEntry p WHERE p.Pricebook2Id =:recEngineBook];
         // Match all of the product ID's in the pricebook with the Recommendation_Response_Product_Number__c
         List<Product2> productList = new List<Product2>();
         Set<Id> prod1 = new set<Id>();

         for(PriceBookEntry s: productIdList){
            prod1.add(s.Product2Id);
         }
         productList = [SELECT Recommendation_Response_Product_Number__c FROM Product2 WHERE Id IN :prod1];
         System.debug('++++++++++++++++++++++++++++++++++++ Product List: ' + productList);

         // Map an ID to each Recommendation Response Product from the ProductList
         Map<ID, product2> matchMap = new Map<ID, product2>(productList);
         Map<String, String> mMap = new Map<String, ID>();
         for(Product2 p : productList){
              mMap.put(p.Recommendation_Response_Product_Number__c, p.id);
         }

         System.debug('++++++++++++++++++++++++++++++++ Map of ID and Product2 : ' + matchMap);

         System.debug('++++++++++++++++++++++++++++++++ mMap: ' + mMap);

         // Id of the current Recommendation Request
         Id recReqId = [SELECT Id FROM Recommendation_Request__c WHERE Id = :ApexPages.currentPage().getParameters().get('Id')].id;
         System.debug('+++++++++++++++++++++++ recReqId: ' + recReqId);

         // Gets the checkbox field, that is checked if a valid recommendation response already exists
            // Used to run Validation Rule to only have one valid recommendation response per request  
         Recommendation_Request__c recReq1 = [SELECT Valid_Recommendation_Response_Exists__c FROM Recommendation_Request__c WHERE Id = :recReqId]; 

         List<Recommendation_Response__c> recResponses = [SELECT Rec_Response_Type__c FROM Recommendation_Response__c WHERE Recommendation_Request__c = :recReqId];
         List<Recommendation_Response__c> oldErrors = new List<Recommendation_Response__c>();
         List<Recommendation_Response__c> validResponse = new List<Recommendation_Response__c>();
         System.debug('List of Rec Responses: ' + recResponses);

           for(Recommendation_Response__c recResp : recResponses){
               // If a valid Recommendation Response already exists, add the response to the Valid Response list
               if(recResp.Rec_Response_Type__c == 'Ideal' || recResp.Rec_Response_Type__c == 'Ideal Filtered' || recResp.Rec_Response_Type__c == 'InBudget'){
                 validResponse.add(recResp);
                    System.debug('+++++++++++++++++++++++++ Valid Recommendation Response Exists!');
               // If an error exists, add the error to the oldErrors List
               } else if(recResp.Rec_Response_Type__c == 'Error'){
                   //if(errorsString != null || errorInvalidKeyString != null){
                       oldErrors.add(recResp);
                   //}
               }
               System.debug('++++++++++++++++++++++++++ RecResponse: ' + recResp);
           }
           System.debug('+++++++++++++++++++++++++++++++ Valid Response: ' + validResponse);
           System.debug('+++++++++++++++++++++++++++++++ Old errors List: ' + oldErrors);

           recReq1.Valid_Recommendation_Response_Exists__c = false; 
           // If a valid response exists, set the Valid Recommendation Response Exists checkbox to true
           if(!validResponse.isEmpty()){
               recReq1.Valid_Recommendation_Response_Exists__c = true;
               System.debug('+++++++++++ Valid Recommendation Response Exists checkbox: ' + recReq1.Valid_Recommendation_Response_Exists__c);
           }

           try{   
               // If there pre-existing errors 
               if(!oldErrors.isEmpty()){
                   if(errorsString != null){
                        System.debug('++++++++++++++++++++++++++ Old Errors is NOT empty...ErrorsString Not Null');
                        delete oldErrors;
                        System.debug('++++++++++++++++++++++++++++++ Old Errors Deleted: ' + oldErrors);
                        insert errorType;
                        System.debug('++++++++++++++++++++++++++++++ New Error Inserted: ' + errorType);
                   } else if(errorInvalidKeyString != null){
                       System.debug('++++++++++++++++++++++ Old Errors is NOT empty...ErrorInvalidKeyString Not Null');
                       delete oldErrors; 
                       System.debug('++++++++++++++++++++++++++ Old Errors Deleted: ' + oldErrors);
                       insert errorInvalidKeyType;
                       System.debug('+++++++++++++++++++++++++++++ New Invalid Key Error Inserted: ' + errorInvalidKeyType);
                   }else{
                       System.debug('++++++++++++++++++++++ Old Errors is NOT empty...Else');
                       delete oldErrors;
                       insert idealType;
                       insert filteredType;
                       insert inBudgetType;
                   }
               // If there are NO pre-existing errors  
               } else {
                   if(errorsString != null){
                       System.debug('++++++++++++++++++++ Old Errors is Empty...ErrorString NOT Null');
                       insert errorType;
                       System.debug('++++++++++++++++++++ Error Type Added!');
                   } else if(errorInvalidKeyString != null){
                       System.debug('+++++++++++++++++++ Old Errors is Empty...ErrorInvalidKeyString NOT Null');
                       insert errorInvalidKeyType;
                       System.debug('++++++++++++++++++++ Error Invalid Key Type Added!'); 
                   } else{
                       System.debug('+++++++++++++++++++ Old Errors is Empty...Else');
                       insert idealType;
                       insert filteredType;
                       insert inBudgetType;
                       System.debug('Types inserted and oldErrors deleted');
                   }
               }
           } catch(DMLException e){
               System.debug('Issue with deleting old RecResponse Errors and Inserting new errors ' + e.getMessage());
           }

         // Ideal       
         if(ideals != null){      
             // Get the values for all Ideal Products, Percent, DollarAmount
             for(Object ideal : ideals){
                 Map<String, Object> i = (Map<String, Object>)ideal;
                 Object idealProduct = i.get('product');
                 Object idealPercent = i.get('percent');
                 Object idealDollarAmount = i.get('dollarAmount');
                 System.debug('++++++++++++++++++++++++++++++++++ Ideal Product: ' + idealProduct);
                 System.debug('++++++++++++++++++++++++++++++++++ Ideal Percent: ' + idealPercent);
                 System.debug('++++++++++++++++++++++++++++++++++ Ideal DollarAmount: ' + idealDollarAmount);

                 String matchProdIdeal = String.valueOf(idealProduct);
                 System.debug('Ideal Product String Value: ' + matchProdIdeal);

                 // Add Recommendation Response Product fields
                 Recommendation_Response_Product__c recResponseProduct = new Recommendation_Response_Product__c();
                 recResponseProduct.Product__c = mMap.get(matchProdIdeal);
                 recResponseProduct.Amount_Recommended__c = Double.valueOf(idealPercent);
                 recResponseProduct.Amount_Recomended__c = Double.valueOf(idealDollarAmount);
                 recResponseProduct.Recommendation_Response__c = idealType.id;

                 // Add Products to a List of Ideal Products
                 idealList.add(recResponseProduct);
             }
         }

         // Ideal Filtered
         if(idealsFiltered != null){   
             for(Object filteredIdeal : idealsFiltered){
                 Map<String, Object> f = (Map<String, Object>)filteredIdeal;
                 Object fIdealProd = f.get('product');
                 Object fIdealPerc = f.get('percent');
                 Object fDollarAmount = f.get('dollarAmount');
                 System.debug('++++++++++++++++++++++++++++++++++ IdealFiltered Product: ' + fIdealProd);
                 System.debug('++++++++++++++++++++++++++++++++++ IdealFiltered Percent: ' + fidealPerc);
                 System.debug('++++++++++++++++++++++++++++++++++ IdealFiltered dollarAmount: ' + fDollarAmount);
                 String matchProdFI = String.valueOf(fIdealProd);

                 // Add Recommendation Response Product fields
                 Recommendation_Response_Product__c recResponseProduct = new Recommendation_Response_Product__c();
                 recResponseProduct.Product__c = mMap.get(matchProdFI);
                 recResponseProduct.Amount_Recommended__c = Double.valueOf(fIdealPerc);
                 recResponseProduct.Amount_Recomended__c = Double.valueOf(fDollarAmount);
                 recResponseProduct.Recommendation_Response__c = filteredType.id;

                 // Add Products to a List of IdealFiltered Products
                 filteredIdealList.add(recResponseProduct);
            }
         }

         // InBudget
         if(inBudgets != null){
             for(Object inBudget : inBudgets){
                 Map<String, Object> ib = (Map<String, Object>)inBudget;
                 Object ibProd = ib.get('product');
                 Object ibPerc = ib.get('percent');
                 Object ibDollarAmount = ib.get('dollarAmount');
                 System.debug('++++++++++++++++++++++++++++++++++ inBudget Product: ' + ibProd);
                 System.debug('++++++++++++++++++++++++++++++++++ inBudget Percent: ' + ibPerc);
                 System.debug('++++++++++++++++++++++++++++++++++ inBudget dollarAmount: ' + ibDollarAmount);
                 String matchProdIB = String.valueOf(ibProd);

                 // Add Recommendation Response Product fields
                 Recommendation_Response_Product__c recResponseProduct = new Recommendation_Response_Product__c();
                 recResponseProduct.Product__c = mMap.get(matchProdIB);
                 recResponseProduct.Amount_Recommended__c = Double.valueOf(ibPerc);
                 recResponseProduct.Amount_Recomended__c = Double.valueOf(ibDollarAmount);
                 recResponseProduct.Recommendation_Response__c = inBudgetType.id;

                 // Add Products to a List of inBudget Products
                 inBudgetList.add(recResponseProduct);
            }
         }

         // Insert the Recommendation Response Products
         try{
             insert idealList;
             insert filteredIdealList;
             insert inBudgetList; 
         }catch(DMLException e){
            System.debug('+++++++++++++++++++ Error Inserting Recommendation Response Products: ' + e.getMessage());
         }

         System.debug('+++++++++++++++++++++++++++ IdealType: ' + idealType);
         System.debug('+++++++++++++++++++++++++++ FilteredType: ' + filteredType);
         System.debug('+++++++++++++++++++++++++++ inBudgetType: ' + inBudgetType);
         System.debug('+++++++++++++++++++++++++++ IdealList: ' + idealList);
         System.debug('+++++++++++++++++++++++++++ FilteredList: ' + filteredIdealList);
         System.debug('+++++++++++++++++++++++++++ inBudgetList: ' + inBudgetList);

       }

    }

Visualforce Page

<apex:page standardController="Recommendation_Request__c" extensions="MicFire">

    <script>
        function redirect(){
            window.history.go(-1);
        }
    </script>

    <apex:form >
        <apex:actionFunction name="basicAuthCallout" action="{!basicAuthCallout}" onComplete="redirect()"></apex:actionFunction>
    </apex:form>

    <script>
        basicAuthCallout();
    </script>

</apex:page>

My Current Test Class (with no code coverage)

@isTest
public class MicFire_Test {

   public class MockHTTPResponseGenerator implements HttpCalloutMock {
       public HTTPResponse respond(HTTPRequest req) {     
           HTTPResponse res = new HTTPResponse();
           res.setHeader('Content-Type', 'application/json');
           res.setStatusCode(200);          
           res.setBody('{"ideal":[{"product":"1","percent":"5","dollarAmount":"1500"}],"idealFiltered":[{"product":"2","percent":"10","dollarAmount":"1500"}],"InBudget":[{"product":"3","percent":"15","dollarAmount":"1500"}]}');
           return res;
        }
    }

    public static testMethod void testHTTPResponse(){
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://testwebservice.com/foo/bar');
        req.setMethod('GET');
        req.setBody('{"ideal":[{"product":"1","percent":"5","dollarAmount":"1500"}],"idealFiltered":[{"product":"2","percent":"10","dollarAmount":"1500"}],"InBudget":[{"product":"3","percent":"15","dollarAmount":"1500"}]}');
        HttpResponse res = h.send(req);
        System.assertEquals('{"ideal":[{"product":"1","percent":"5","dollarAmount":"1500"}],"idealFiltered":[{"product":"2","percent":"10","dollarAmount":"1500"}],"InBudget":[{"product":"3","percent":"15","dollarAmount":"1500"}]}', res.getBody());
        System.assertEquals(200, res.getStatusCode());
    }

    public static testMethod void createAccount(){
        Market__c m = new Market__c(Name='test', Unit_Number__c='1111');
        insert m;

        Account a = new Account(Name='test account', Market__c = m.id);
        insert a; 

        System.assertEquals('test account', a.name);
    }

    public static testMethod void validateRecommendationRequest(){
        Market__c m = new Market__c(Name='test', Unit_Number__c='1111');
        insert m;

        Account a = new Account(Name='test account', Market__c = m.id);
        insert a; 

        Recommendation_Request__c recReq = new Recommendation_Request__c(Account_Rec__c = a.id, Budget__c = 62500, Customer_Objective_1__c = 'Increase brand equity', Customer_Objective_1_Age__c = 'M18-34', REST_API_Parms__c = 'customer=a2Oc00000007DSG&segment=A&budget=62500&mo1=B_M18_0&exclude=0');
        insert recReq;

        System.assertEquals('Increase brand equity', recReq.Customer_Objective_1__c);
    }

    public static testMethod void createRecResponse(){
        Market__c m = new Market__c(Name='test', Unit_Number__c='1111');
        insert m;

        Account a = new Account(Name='test account', Market__c = m.id);
        insert a; 

        Recommendation_Request__c recReq = new Recommendation_Request__c(Account_Rec__c = a.id, Budget__c = 62500, Customer_Objective_1__c = 'Increase brand equity', Customer_Objective_1_Age__c = 'M18-34', REST_API_Parms__c = 'customer=a2Oc00000007DSG&segment=A&budget=62500&mo1=B_M18_0&exclude=0');
        insert recReq;

        Recommendation_Response__c recResp1 = new Recommendation_Response__c(Rec_Response_Type__c = 'Ideal', Recommendation_Request__c = recReq.id);
        Recommendation_Response__c recResp2 = new Recommendation_Response__c(Rec_Response_Type__c = 'Ideal Filtered', Recommendation_Request__c = recReq.id);
        Recommendation_Response__c recResp3 = new Recommendation_Response__c(Rec_Response_Type__c = 'InBudget', Recommendation_Request__c = recReq.id);

        insert recResp1;
        insert recResp2;
        insert recResp3; 

        System.assertEquals('Ideal', recResp1.Rec_Response_Type__c);
        System.assertEquals('Ideal Filtered', recResp2.Rec_Response_Type__c);
        System.assertEquals('InBudget', recResp3.Rec_Response_Type__c);
    }

    public static testMethod void createRecResponseProducts(){
        Market__c m = new Market__c(Name='test', Unit_Number__c='1111');
        insert m;

        Account a = new Account(Name='test account', Market__c = m.id);
        insert a; 

        Recommendation_Request__c recReq = new Recommendation_Request__c(Account_Rec__c = a.id, Budget__c = 62500, Customer_Objective_1__c = 'Increase brand equity', Customer_Objective_1_Age__c = 'M18-34', REST_API_Parms__c = 'customer=a2Oc00000007DSG&segment=A&budget=62500&mo1=B_M18_0&exclude=0');
        insert recReq;

        Recommendation_Response__c recResp1 = new Recommendation_Response__c(Rec_Response_Type__c = 'Ideal', Recommendation_Request__c = recReq.id);    
        insert recResp1;

        Product2 prod = new Product2(Name='Test Product', Recommendation_Response_Product_Number__c = '2');
        insert prod;

        Recommendation_Response_Product__c recRespProd1 = new Recommendation_Response_Product__c(Product__c = prod.id, Amount_Recommended__c = 23, Amount_Recomended__c = 30, Recommendation_Response__c = recResp1.id);
        insert recRespProd1;

        System.assertEquals(prod.id, recRespProd1.Product__c);
    }

    public static testMethod void linkRecResponseToRecProduct(){
        Market__c m = new Market__c(Name='test', Unit_Number__c='1111');
        insert m;

        Account a = new Account(Name='test account', Market__c = m.id);
        insert a; 

        Recommendation_Request__c recReq = new Recommendation_Request__c(Account_Rec__c = a.id, Budget__c = 62500, Customer_Objective_1__c = 'Increase brand equity', Customer_Objective_1_Age__c = 'M18-34', REST_API_Parms__c = 'customer=a2Oc00000007DSG&segment=A&budget=62500&mo1=B_M18_0&exclude=0');
        insert recReq;

        Recommendation_Response__c recResp1 = new Recommendation_Response__c(Rec_Response_Type__c = 'Ideal', Recommendation_Request__c = recReq.id);    
        insert recResp1;

        Product2 prod = new Product2(Name='Test Product', Recommendation_Response_Product_Number__c = '2');
        insert prod;

        Recommendation_Response_Product__c recRespProd1 = new Recommendation_Response_Product__c(Product__c = prod.id, Amount_Recommended__c = 23, Amount_Recomended__c = 30, Recommendation_Response__c = recResp1.id);
        insert recRespProd1;

        System.assertEquals(recResp1.Id, recRespProd1.Recommendation_Response__c);
    }
}

Best Answer

You are not actually testing anything in your MicFire class. All you are doing in your test method is creating new code. In addition the createAccount method does not cause anything in your class to execute unless you have a trigger on account the calls the class.

Below is a start to what you should be doing

@isTest
public class testExample{

  public static test method void basicTest(){
    MicFire con = New MicFire();

    test.startTest();
      Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
      con.basicAuthCallout();
    test.stopTest();

    //Do some assertions to make sure the data is correct or events actually occured
  }

}

There is plenty of documentation on writing test classes. You are not creating new code, rather you need to set up the database / paramters, execute or invoke the code you are testing, then check for results.

Related Topic