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
ganesh jadhavganesh jadhav 

increase code coverage

Hi I'm trying to write test cases using isTest annotation

first of all i have initialized my visualforce page.

than initialized the controller

and iam calling each methods in controller

 

but in my code coverage is only 76% only....... i know 75% code coverage is enough for deploy code in production organization but iam expecting 100% code coverage here is my code please let me any suggesions

 

Here is mine Controller

in mine controller logic is reda csv file and display in to some vf page

 

//Create Controller For Import CSV File and Insert itnto Database
public class CSVcontroller {    
    public Blob uploadFile{ get; set; }
    public String nameFile { get; set; }
    public Integer colCount { get; set; }
    public String row {get; set;}
    public Integer rowCount { get; set; }
    public String fileString { get; set; }    
    //Insert Action for inserting the csv data into Fund_Management object
    @RemoteAction
    public static void insertAccounts(List<Fund_Management__c> fundlist){                 
        try{
            //Schema.DescribeFieldResult fId = Fund_Management__c.fnameMonthYear__c.getDescribe();
            //Schema.sObjectField T = fId.getSObjectField();
            Schema.SObjectField fId = Fund_Management__c.Fields.fnameMonthYear__c;
            //upsert(fundlist,fId,false);
            //insert fundlist;            
            //Database.Upsert(fundlist,fId,false);
              upsert fundlist fnameMonthYear__c;                      
            }catch(DmlException e) {
                System.debug('An unexpected error has occurred: ' + e.getMessage());
            }
       }
    
    public List<List<String>> getResults() {        
       List<List<String>> parsedCSV = new List<List<String>>();
       rowCount = 0;
       colCount = 0;
       if (uploadFile!= null){
            fileString = uploadFile.toString();       
            parsedCSV = parseCSV(fileString, false);
            rowCount = parsedCSV.size();
            for (List<String> row : parsedCSV){
               if (row.size() > colCount){
               colCount = row.size();
               }
            }
       }
       System.debug('nameFile' + nameFile);
       return parsedCSV;
     }
     public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) {
         List<List<String>> allFields = new List<List<String>>();
         // replace instances where a double quote begins a field containing a comma
         // in this case you get a double quote followed by a doubled double quote
         // do this for beginning and end of a field
         contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
         // now replace all remaining double quotes - we do this so that we can reconstruct
         // fields with commas inside assuming they begin and end with a double quote
         contents = contents.replaceAll('""','');
         // we are not attempting to handle fields with a newline inside of them
         // so, split on newline to get the spreadsheet rows
         List<String> lines = new List<String>();
         try {
         lines = contents.split('\r'); // using carriage return accomodates windows, unix, and mac files
         }
         catch (System.ListException e) {
         System.debug('Limits exceeded?' + e.getMessage());
         }
         Integer num = 0;
         for(String line: lines){
             // check for blank CSV lines (only commas)
             if (line.replaceAll(',','"').trim().length() == 0) break;
                 List<String> fields = line.split(',');
                 List<String> cleanFields = new List<String>();
                 System.debug('fields' + fields );
                 String compositeField;
                 Boolean makeCompositeField = false;
     
                 for(String field: fields) {
                     if (field.startsWith('"') && field.endsWith('"')) {
                     cleanFields.add(field.replaceAll('DBLQT',''));
                     }
                     else if (field.startsWith('"')) {
                     makeCompositeField = true;
                     compositeField = field;
                     }
                     else if (field.endsWith('"')) {
                     compositeField += ',' + field;
                     cleanFields.add(compositeField.replaceAll('DBLQT',''));
                     makeCompositeField = false;
                     }
                     else if (makeCompositeField){
                     compositeField +=  ',' + field;
                     }
                     else {
                     cleanFields.add(field.replaceAll('',''));
                     }
                }
                allFields.add(cleanFields);
            }
        //if (skipHeaders) allFields.remove(0);
        return allFields;     
     }
    public void checkblankfile(){
        if(rowCount == 0) {
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'The file is empty.'));
        }        
     }
    public PageReference vfReciredt(){         
        if(uploadFile ==null) {
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Upload File'));
        }
        else{
            //PageReference redirect = new PageReference('/apex/Fund_List?sfdc.tabName=01r900000007xyR');
            //redirect.setRedirect(true);
            //return redirect;
        }
        return null;
    }

}

 

 highlighted area is not get covered anybody knows to get code coverage for that area..... and also let me know how to increase code coverage for code included in conditional statements like  for, if, else conditions

 

and here is mine Test class

 

@isTest
private class csvControllerTest
{    
   static testMethod void myUnitTest() {
        
        //Test converage for the cumulativePerformanceChart visualforce page        
        PageReference pageRef = Page.ImportCSV;
        Test.setCurrentPageReference(pageRef);          
        // Perform our data preparation.
        //Insert Single Record
        Fund_Management__c fmssr = new Fund_Management__c(Fund_Name__c='test fund',Growth__c=1.2,Month__c='Jan',Year__c=2008);
        insert fmssr;
        //Insert Bulk Record
        List<Fund_Management__c> fmsbr = new List<Fund_Management__c>{};
                 
        for(Integer i = 0; i < 200; i++){
            Fund_Management__c f = new Fund_Management__c(Fund_Name__c = 'Test Fund '+i,Growth__c = 1.2,Month__c = 'Jan',Year__c = 2008);
            fmsbr.add(f);
        }        
         //Now insert data causing an contact trigger to fire.
        Test.startTest();
        try {
             insert fmsbr;        
        }catch(DmlException e) {
           
            }       
        Test.stopTest();       
        // Query the database for the newly inserted records.
        List<Fund_Management__c> insertedFunds = [SELECT Fund_Name__c, Growth__c ,Month__c,Year__c FROM Fund_Management__c];             
        // Assert that the Description fields contains the proper value now.
        for(Fund_Management__c a : insertedFunds){
        System.assert(insertedFunds != null);
        }        
    
        String csvContent = 'Test,Jan,2001,3,l\nTest1,Feb,2001,4,k';
        //initialization of csvcontroller
        CSVcontroller csv = new CSVcontroller();
        List<List<String>> parsedCSV = CSVcontroller.parseCSV(csvContent,false);
        system.assertEquals(parsedCSV[0][0],'Test');
        system.assertEquals('Jan',parsedCSV[0][1]);
        system.assertEquals('2001',parsedCSV[0][2]);
        system.assertEquals('3',parsedCSV[0][3]);
        //Call All Methods In CsvController
         csv.getResults();
         csv.vfReciredt();
         csv.checkblankfile();           
         CSVcontroller.insertAccounts(fmsbr);
    }
}

 

in that i have write the insert logic for 1 records and insert logic for 200 records still not getting 100 % code coverage

gautam_singhgautam_singh

Hi,


Following two points will cover your code. I had done a fairly same scenario of csv parsing earlier. You can check that here.

Follow these phrase, It will end the search for your requirement.

You have to insert a file say attach before the class initialization and then csv.uploadFile, Give this variable direct values and it will cover the red quote.

In the dummy values which you are inserting String csvContent = 'Test,Jan,2001,3,l\nTest1,Feb,2001,4,k'; add some values in Double Quote , as that will take the 2nd red clause to cover.


Important :

Hit Kudos if this provides you with useful information and if this is what you where looking for then please mark it as a solution for other benefits.

Thank You





ganesh jadhavganesh jadhav

Yesi have added this code as well!!! you can see in above code still not getting 100% code coverage

satheesh8.k1.3890099515516848E12satheesh8.k1.3890099515516848E12
Hi ganesh,

Please provide total test class .

I am also facing same issue.

Please help me 

Thanks
Satheesh