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
Øyvind Borgersen 10Øyvind Borgersen 10 

Test class file upload

Hi,

I have a test class which I'm struggling to get a 100% cover. I have the following test class: 

@isTest
public class ImportDataFromCSVControllerTest {
    static String str = 'Case_ID__c,Number_of_copies__c,Registration_date__c\n a031X000002TdIBQA0,40,2019-05-18\n a031X000002TdIBQA0,40,2019-05-19';       

    public static String[] csvFileLines;
    public static Blob csvFileBody;

    static testmethod void testfileupload(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.csvFileBody = csvFileBody;
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegative(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.importCSVFile();
        Test.stopTest();
    }
    static testmethod void testfileuploadalt(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.csvFileBody = csvFileBody;
        importData.importCSVFile();
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegativealt(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.importCSVFile();
        Test.stopTest();
    }
}


The lines below are the ones which are not covered by the class. Can someone help me with the necessary code to add to the test class?



                vidObj.Case_ID__c = csvRecordData[0];
                vidObj.RegistrationNumberDummy__c = csvRecordData[1];
                //vidObj.RegistrationNumberDummy__c = dateString;
                vidObj.Titledummy__c = csvRecordData[2];
                vidObj.Number_of_copies__c = decimal.valueof(csvRecordData[3].trim());
                vidObj.Registration_date__c = date.today();
                vidList.add(vidObj);
                }
            }
            insert vidList;
            if(!vidList.isempty()){
                system.debug('vidlist' + vidlist);

                ApexPages.Message successMessage = new ApexPages.Message(ApexPages.severity.CONFIRM,' File successfully uploaded');
                ApexPages.addMessage(successMessage);}
                            else {
                ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,' An error has occured while importing data Please make sure input csv file is correct nad that salesnumber not already is uploaded in this quarter');
                ApexPages.addMessage(errorMessage);}
 
ApuroopApuroop
You need to post the full class in order to pin down the issue.
Øyvind Borgersen 10Øyvind Borgersen 10
Hi Apuroop,

Here's the complete class:

public class importDataFromCSVController {
    public Blob csvFileBody{get;set;}
    public string csvAsString{get;set;}
    public String[] csvFileLines{get;set;}
    public List<Videogram_sales_number__c> vidList{get;set;}
    public importDataFromCSVController(){
        csvFileLines = new String[]{};
             vidList = New List<Videogram_sales_number__c>();

    }
    public void importCSVFile(){
        try{
            csvAsString = csvFileBody.toString();
            csvFileLines = csvAsString.split('\n');

            for(Integer i=1;i<csvFileLines.size();i++){
                Videogram_sales_number__c vidObj = new Videogram_sales_number__c();
                
                //Create date as string
                String dateFormatString = 'yyyy-MM-dd';
                Date d = Date.today();
                Datetime dt = Datetime.newInstance(d.year(), d.month(),d.day());
                String dateString = dt.format(dateFormatString);

                //Split by comma or semicolon
                string[] csvRecordData = csvFileLines[i].split(',|\\;');

                if(!(csvRecordData[3] =='')){
                vidObj.Case_ID__c = csvRecordData[0];
                vidObj.RegistrationNumberDummy__c = csvRecordData[1];
                vidObj.Titledummy__c = csvRecordData[2];
                vidObj.Number_of_copies__c = decimal.valueof(csvRecordData[3].trim());
                vidObj.Registration_date__c = date.today();
                vidList.add(vidObj);
                }
            }
            insert vidList;
            if(!vidList.isempty()){
                system.debug('vidlist' + vidlist);

                ApexPages.Message successMessage = new ApexPages.Message(ApexPages.severity.CONFIRM,'Fil er korrekt lastet opp // File successfully uploaded');
                ApexPages.addMessage(successMessage);}
                            else {
                ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'En feil har oppstått, vennligst sjekk at filen er korrekt og at salgstall ikke allerede er rapportert i dette kvartal // An error has occured while importing data Please make sure input csv file is correct nad that salesnumber not already is uploaded in this quarter');
                ApexPages.addMessage(errorMessage);}
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importing data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
    }
}
ApuroopApuroop
In your class, you have the Try-Catch block, that's the reason you weren't able to catch the errors when running the test.

I modified the test class and was able to get 94%. I could get 100% if I understood what are the required fields on Videogram Sales Number object.
@isTest
public class ImportDataFromCSVControllerTest {
    
    static String strHeader = 'Case_ID__c,RegistrationNumberDummy__c,Titledummy__c,Number_of_copies__c,Registration_date__c\n';

    public static String[] csvFileLines;
    public static Blob csvFileBody;

    static testmethod void testfileupload(){
        Case newCase1 = new Case(Status='New', Origin='Phone');
        Case newCase2 = new Case(Status='New', Origin='Phone');
        insert newCase1;
    	insert newCase2;
		
        String firstRow = newCase1.Id+',54321,DummyTitle1,40,2019-05-18\n';
        String secondRow = newCase2.id+',987654,DummyTitle2,40,2019-05-19';
        String str = strHeader + firstRow + secondRow;
        
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.csvFileBody = csvFileBody;
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegative(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(strHeader);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.importCSVFile();
        Test.stopTest();
    }
    static testmethod void testfileuploadalt(){
        Case newCase1 = new Case(Status='New', Origin='Phone');
        Case newCase2 = new Case(Status='New', Origin='Phone');
        insert newCase1;
    	insert newCase2;
		
        String firstRow = newCase1.Id+',54321,DummyTitle1,40,2019-05-18\n';
        String secondRow = newCase2.id+',987654,DummyTitle2,40,2019-05-19';
        String str = strHeader + firstRow + secondRow;
        System.debug('firstRow::::: '+firstRow);
        System.debug('secondRow::::: '+secondRow);
        System.debug('str::::: '+str);
        Test.startTest();       
        csvFileBody = Blob.valueOf(str);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.csvFileBody = csvFileBody;
        importData.importCSVFile();
        Test.stopTest();
    } 

    static testmethod void testfileuploadNegativealt(){
        Test.startTest();       
        csvFileBody = Blob.valueOf(strHeader);
        String csvAsString = csvFileBody.toString();
        csvFileLines = csvAsString.split('\n'); 

        ImportDataFromCSVController importData = new ImportDataFromCSVController();
        importData.importCSVFile();
        Test.stopTest();
    }
}

Few points before you try out..
  • In the test class that you wrote, in the str String, there's an ID starting with 'a03---'. This is not a standard Case object. So if this is a custom object, then you have to create a couple of records and replace them with the Case records in the above test class.
  • On line 27 in your Original class, I didn't understand the reason why you're checking the third element of the string array. I'd say use something like, if(csvRecordData.size() <= 5) - with this you are making sure that we have the data for all the fields.
  • The error before doing this edit is the list index was out of bounds. csvRecordData[3] didn't have any data in it.
  • I just created those fields in my dev org based on the nomenclature, pretty sure yours would be different. My suggestion would be, comment out just the try and catch statements. You can see what exactly is the error.
  • In your test class, add more assert statements and make sure you are returning the expected results.
Let me know how it turns out. :)
Susmitha T 5Susmitha T 5
I need to add case with attachment in salesforce from our website, In web-to-case that is not possible directly.. so workaround is 
using apis like first ineed to create case then attach files to it.

Iwrite code for file uploading like
@RestResource(urlMapping='/DocumentUpload/*')
global class fileuploaderapi{
 
    @HttpPost
global static void uploadDocument()
{
RestRequest req = RestContext.request;
RestResponse res = Restcontext.response;
Id recId = req.params.get('recordId');
string contenttype = req.params.get('contenttype');
string name = req.params.get('name');
Blob myBlob=Blob.valueOf(name);
try
{
        //Insert ContentVersion
        ContentVersion cVersion = new ContentVersion();
        cVersion.PathOnClient = name;//File name with extention
        cVersion.Title = name;//Name of the file
        cVersion.VersionData = req.requestBody;//File content
        Insert cVersion;

        //After saved the Content Verison, get the ContentDocumentId
        Id conDocument = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cVersion.Id].ContentDocumentId;

        //Insert ContentDocumentLink
        ContentDocumentLink cDocLink = new ContentDocumentLink();
        cDocLink.ContentDocumentId = conDocument;//Add ContentDocumentId
        cDocLink.LinkedEntityId = recId;//Add attachment parentId
        Insert cDocLink;

        RestContext.response.addHeader('Content-Type', 'application/json');
        RestContext.response.responseBody = Blob.valueOf(generateJSON('Success',conDocument,''));

        }
        catch(Exception e)
        {
        RestContext.response.addHeader('Content-Type', 'application/json');
        RestContext.response.responseBody = Blob.valueOf(generateJSON('Error','',e.getMessage()));
        }

        }
        // To generate JSON response
        private static string generateJSON(String Status,String Content,String error){
        JSONGenerator jsGen = JSON.createGenerator(true);
        jsGen.writeStartObject();
        jsGen.writeStringField('Status',Status);
        jsGen.writeStringField('ContentID', Content);
        jsGen.writeStringField('Error', error);
        jsGen.writeEndObject();
        return jsGen.getAsString();
        }
      }
    

It is successfull but i'm getting error for testclass code coverage
My test class is 
@isTest
public class fileuploadapitestclass {
     static testMethod void testMethod1() 
     {
    // Account acc = [ SELECT Id FROM Account where LastModifiedById!=null LIMIT 1 ];
    Case c=new Case();
        c.Subject='test';
        insert c;
       StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'GetcaseResource' LIMIT 1];
String body =  EncodingUtil.base64Encode(sr.Body);
        
        
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse();             
        req.requestURI = '/services/apexrest/DocumentUpload/' ;
        req.httpMethod = 'POST';
        req.addHeader('Content-Type', 'application/json');
         req.addHeader('Content-Type','image/jpeg');
        RestContext.request = req;
        RestContext.response= res;
        Id recId =c.Id;
        string contenttype = 'contenttype';
        string name = 'testname';
        //Blob myBlob=Blob.valueOf(name);
       
        ContentVersion cVersion = new ContentVersion();
        cVersion.Title = name;//Name of the file 
        cVersion.PathOnClient = 'testname.jpg';//File name with extention
       
        cVersion.VersionData =Blob.valueOf(body );//File content
        Insert cVersion;

        //After saved the Content Verison, get the ContentDocumentId
        Id conDocument = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:cVersion.Id].ContentDocumentId;

        //Insert ContentDocumentLink
        ContentDocumentLink cDocLink = new ContentDocumentLink();
        cDocLink.ContentDocumentId = conDocument;//Add ContentDocumentId
        cDocLink.LinkedEntityId = recId;//Add attachment parentId
        Insert cDocLink;

       
     Test.setMock(HttpCalloutMock.class, new SMSCalloutMock());
      
       fileuploaderapi.uploadDocument();
        string Status;
        string Content;
        string error;
         JSONGenerator jsGen = JSON.createGenerator(true);
        jsGen.writeStartObject();
        jsGen.writeStringField('Status',Status);
        jsGen.writeStringField('ContentID', Content);
        jsGen.writeStringField('Error', error);
        jsGen.writeEndObject();
        Test.stopTest();
    }  

}
--------------------
I also tried not using static resource but no luck
Can any one help me solving my issue