Search code examples
visualforceapex

cant able to test file extension on test class?


visuaforce page:

<apex:page sidebar="false" controller="UploadOpportunityScheduleLineItem123">
    <apex:form >
        <apex:sectionHeader title="Upload data from CSV file"/>
          <apex:pagemessages />  
            <center>
                <apex:inputFile value="{!contentFile}" filename="{!nameFile}" />
                <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
                <br/> <br/>
            </center>  
   </apex:form>   
</apex:page>

apex:

public with sharing class UploadOpportunityScheduleLineItem123{

    // Global variables
    public string nameFile{get;set;}


    Public Id parentId{get;set;}

    public Blob contentFile{get;set;}


    List<account> lstScheduleToUpdate = new List<account>();

    public account objSchedule{get;set;}
    //String array for taking csv data by line.
    String[] filelines = new String[]{};


    //set for storing all id's from csv.
    set<String> opptoupload{get;set;}



       //Main constructor
    public UploadOpportunityScheduleLineItem123()
    {
        //Initalizing required objects.
        objSchedule = new account();
        opptoupload = new set<String>();

    }
    //Method to read file content and check extension and file format.
    public Pagereference ReadFile()
    {

        parentId=Apexpages.currentPage().getParameters().get('ParentId');
        //If without selecting csv file you clicked on upload it will give error message.
      if(nameFile == null)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'You should select csv file to upload');
            ApexPages.addMessage(errormsg);
            return null;
        }
        //Taking file extension.
        String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
        //Checking if file extension is .csv.
        if(extension == 'csv' ||extension == 'CSV')
        { 
            nameFile =blobToString( contentFile,'ISO-8859-1');
            //Spliting by new line

            filelines = nameFile.split('\n');
            //Spliting values by (,) for checking coloumn size

                for (Integer i=1;i<filelines.size();i++){               
                String[] inputconvalues = new String[]{};
                inputconvalues = filelines[i].split(',');
                account b = new account();
                b.name= inputconvalues[0];
                b.billingcountry = inputconvalues[1];
                b.billingcity = inputconvalues[2];
                lstScheduleToUpdate.add(b);                
                }
                //Checking if list is not empty then updating.
                if(lstScheduleToUpdate.Size()>0)
                {
                    insert lstScheduleToUpdate;
                }
                ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.info,'Batches File uploaded successfully');
                ApexPages.addMessage(errormsg);
            return null;
        }
        //If file is not csv type then it will give error message.
        else
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'File type should be csv type');
            ApexPages.addMessage(errormsg);
            return null;
        }
    }
    public static String blobToString(Blob input, String inCharset){
        String hex = EncodingUtil.convertToHex(input);
        System.assertEquals(0, hex.length() & 1);
        final Integer bytesCount = hex.length() >> 1;
        String[] bytes = new String[bytesCount];
        for(Integer i = 0; i < bytesCount; ++i)
        bytes[i] =  hex.mid(i << 1, 2);
        return EncodingUtil.urlDecode('%' + String.join(bytes, '%'), inCharset);
    }    
}

test class :

@IsTest(SeeAllData=true)

    private class testexceltoaccount
    {
          static testmethod void testLoadData() {
                   StaticResource testdoc = [Select Id,Body from StaticResource where name ='testMethodCSVUpload1'];
             UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
             testUpload.contentFile= testdoc.Body;
             testUpload.ReadFile();
              }

    }

Cant able to cross this section of code in code coverage :

String extension = nameFile.substring(nameFile.lastIndexOf('.')+1);
        //Checking if file extension is .csv.
        if(extension == 'csv' ||extension == 'CSV')
        {

I tried many possible to cross code coverage but still it is at that point .Please help me in this regard.

Thanks in advance


Solution

  • When we use apex:inputFile on VF page and upload any file, then name of file is automatically update field into the field specified in filename attribute, but when you are writing test class you only specifying content of file testUpload.contentFile= testdoc.Body; You should add name in nameFile global variable manually testUpload.nameFile= 'test.csv';

    @IsTest(SeeAllData=true)
    private class testexceltoaccount
    {
          static testmethod void testLoadData() {
                   StaticResource testdoc = [Select Id,Body,Name from StaticResource where name ='testMethodCSVUpload1'];
             UploadOpportunityScheduleLineItem123 testUpload = new UploadOpportunityScheduleLineItem123();
             testUpload.contentFile= testdoc.Body;
             testUpload.nameFile= 'test.csv';
             testUpload.ReadFile();
              }
    
    }