• Susmitha T 5
  • NEWBIE
  • 0 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 2
    Replies


How to write test class for document uplaodapi using restapi

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 

Susmitha 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 
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);}