+ Start a Discussion
Salesforce Developer 60Salesforce Developer 60 

How to increase test coverage for api class

Hello Team ,
                  I created below api class and it's test class but am getting 21% test coverage how to increase this test coverage?

This is my api class
 
public class ClientRepository {

    public ClientRepository(ApexPages.StandardController controller) {

    }

    public String message {get; set;}
    //public String input{get;set;}
    
    public PageReference GetInvoiceSummary( ) { 
        string accesstoken;
        InvoiceSummaryDetail invoiceDetail = new InvoiceSummaryDetail();
        HttpRequest req = new HttpRequest();
        HttpResponse res = new HttpResponse();
        Http http = new Http();
        Id accId= Apexpages.currentPage().getParameters().get('Id');
        Account acc=[select id,CRXIS_Client_ID__c from Account where Id=:accId];
         String strId = Id.valueOf(acc.Id);
        
        if(acc.CRXIS_Client_ID__c !=null)
        {
        
                Integer ClientId =integer.valueof(acc.CRXIS_Client_ID__c);
                system.debug(ClientId );
                SessionData__c objToken = [select Access_Token1__c,Access_Token2__c,Access_Token3__c from SessionData__c where Name='token2'];
                 accesstoken =objToken.Access_Token1__c+objToken.Access_Token2__c+objToken.Access_Token3__c;
                system.debug(accesstoken);
                req.setHeader('Authorization','Bearer '+accesstoken);
                req.setMethod('GET');
                req.setEndpoint('http://google.com/?ClientID='+ClientId);
        
                try {
                     res = http.send(req);
                   
                     message =  res.getBody();
                     invoiceDetail = (InvoiceSummaryDetail)JSON.deserialize(message, InvoiceSummaryDetail.class);
        
                     System.debug(invoiceDetail);
                     System.debug(res.getBody());
                    
               
            
    
   List<Invoice__c> objInvo =[Select Name,Customer__c,InvoiceID__c FROM Invoice__c where Customer__c=:acc.Id]; 
          
         
          system.debug(objInvo.size());  
               if(objInvo.size()<=0){
List<Invoice__c> invoiceList = new List<Invoice__c>();

   
               
for(InvoiceSummary iData:invoiceDetail.ListInvoiceSummary)
{    Invoice__c objInvoice=new Invoice__c();   
    objInvoice.Customer__c =acc.Id;  
        /*System.debug(iData.InvoiceAmount);*/
    objInvoice.BalanceDue__c=iData.BalanceDue;
    objInvoice.InvoiceID__c=iData.InvoiceId;
    objInvoice.InvoiceAmount__c=iData.InvoiceAmount;
    date parsedDate = date.parse(iData.InvoiceDate);
    Integer years =parsedDate.year();
    objInvoice.InvoiceYear__c =string.valueof(years) ;
   objInvoice.InvoiceDate__c=parsedDate;
    objInvoice.InvoiceNumber__c=iData.InvoiceNumber;
    objInvoice.InvoiceType__c=iData.InvoiceType;
    objInvoice.TotalCases__c=iData.TotalCase;
    invoiceList.add(objInvoice);
  
}

  insert invoiceList;
               }
               else{
               
               system.debug('Already Invoice');
               }


            
        
          } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
            message = res.getBody();
            System.debug(res.getBody());
          }
          }
            return null;
        
  }

}

This is my mockcallout class
 
@isTest
global class MockHttpResponseGeneratorInvoice implements HttpCalloutMock {
   // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
          String accesstoken ='3YWiojf9Qe88XSLrlZrZZqlKPg8NWanYrs1kDy0M_8tWXeO8e4u0cmnTdePUa9lfhoDRikUmXqgCh_hwD6Sv_gJTx3rOu0fPUSpMX8vIeuuzeAUX27cY897ZtAh-WSnwxzlMOQ5jFcuDZWadL5FM6F4OgAaSwyxRHSBoKvp9lU7M0fPaEiN-5E1iX3n1D3BLPzb3CUBtlfrKAzCBQB4gWj_lF4ggFCtTVPvXHhTKqWxYjc7czW83DhoQDJa2vqeYKGHHex_X77n_K4N-ASZzJhjJvG_F7u6mTdTOBlxsBpb_SgFsvLMmPl2aIyoz_-C341VDkKShObWBuXULaLTM0O4n64IrRiwGbIhq4Eh9SAmnkGTjSljPexEWnJMfSW_6fa9Qj2HKw7OyleFVcZYfTNFx_rmeDawAvGOhoZdNREl5bqNHY3RbEFSArgrI0onp0YFk2KePK5YFj-q-NiZvkh2ZruLY3GB1fFNbNTaVAGkXkp9b0vA8ReLk_Cuji6av';
        req.setHeader('Authorization','Bearer '+ accesstoken);
        
        System.assertEquals('http://google.com/GetInvoiceSummary?ClientID='+12, req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
  
       // Create a fake response
        HttpResponse res = new HttpResponse();
       // res2.setHeader('Content-Type', 'application/json');
       // res2.setStatusCode(200);
        res.setBody('{"ClientId":12,"ClientName":"Nrt","ListInvoiceSummary":[{"InvoiceId":1,"InvoiceNumber":"10031","InvoiceDate":"6/27/2008","InvoiceType":"Full Paid","InvoiceTypeId":null,"IsFullPaid":true,"InvoiceAmount":"12","BalanceDue":0.0,"TotalCase":1},{"InvoiceId":2,"InvoiceNumber":"10036","InvoiceDate":"7/30/2008","InvoiceType":"Full Paid","InvoiceTypeId":null,"IsFullPaid":true,"InvoiceAmount":"16","BalanceDue":0.0,"TotalCase":1}]}');
        
        system.debug(res.getBody());
        return res;
    }
This is my callouttest class
 
@isTest
private class CalloutClassTest2 {
public CalloutClassTest2(){
        }
     @isTest static void testCallout2() {
       // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGeneratorInvoice());  
       // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock.
        Account a = new Account();
        a.Name = 'Test';
        a.CRXIS_Client_ID__c ='30';
        insert a;
        
        Invoice__c inv = new Invoice__c();
        //inv.Name ='test';
        inv.Customer__c ='001280000035FQG';
        inv.InvoiceID__c  ='001280000035FQG';
        insert inv;
        
        ApexPages.CurrentPage().getparameters().put('id', a.id);
        ApexPages.StandardController sc = new ApexPages.standardController(a); 
        ClientRepository w = new ClientRepository (sc);
        ClientRepository con = New ClientRepository (New ApexPages.StandardController(a));
        con.GetInvoiceSummary();
        
        
    }
}


 
NagaNaga (Salesforce Developers) 
Hi Salesforce Developer,

You can test callouts using the mockinterfaces provided by the force.com framework or loading data from static resources. Actually running a callout from test context is not possible (and not really desired).

Have a look at the documentation about this: 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_restful_http_testing.htm

Best Regards
Naga Kiran
Salesforce Developer 60Salesforce Developer 60
I already implement this but not able to cover test coverage. Take a look above code
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class. I hope that will help you
@isTest
private class CalloutClassTest2 
{
     @isTest static void testCallout2() 
	 {
       // Set mock callout class
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGeneratorInvoice());  
       // Call method to test.
        // This causes a fake response to be sent from the class that implements HttpCalloutMock.
		
        Account acc = new Account();
        acc.Name = 'Test';
        acc.CRXIS_Client_ID__c ='30';
        insert acc;
        
        Invoice__c inv = new Invoice__c();
        //inv.Name ='test';
        inv.Customer__c =acc.id;
        inv.InvoiceID__c  ='001280000035FQG'; // Pleas create data add valid id here same like above line
        insert inv;
        
        ApexPages.CurrentPage().getparameters().put('id', a.id);
        ApexPages.StandardController sc = new ApexPages.standardController(a); 
		
        ClientRepository w = new ClientRepository (sc);
        ClientRepository con = New ClientRepository (New ApexPages.StandardController(a));
        con.GetInvoiceSummary();
        
        
    }
}

Please let us know if this will help you
Thanks
Amit Chaudhary
Salesforce Developer 60Salesforce Developer 60
@Amit , i tried your solution now test coverage is 24%. How to increase more.