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
studiopikastudiopika 

Document object in TestMethod

I'm trying to write a testmethod for an apex class that reads a file from Visual Force <apex:inputFile> and process the file.

I'm trying to add the test file to Document object and read the body of that document in my testMethod but that seems to be a problem as nothing was returned from the query even though the same query works fine in the class body. So testMethod can't access Document Object? Is that the right way to test a input file? Or I have to construct a Blob somehow on the fly? Or any other ways to let the test method read a file?

 

Thank you very much for any leads.

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

You can encode a test document as a base64 string, then hand that value to the blob object you've bound to your inputfile's body attribute.

 

Blob v = EncodingUtil.base64Decode('WW91IGNhbiBlbmNvZGUgYSB0ZXN0IGRvY3VtZW50IGFzIGEgYmFzZTY0IHN0cmluZywgdGhlbiBoYW5kIHRoYXQgdmFsdWUgdG8gdGhlIGJsb2Igb2JqZWN0IHlvdSd2ZSBib3VuZCB0byB5b3VyIGlucHV0ZmlsZSdzIGJvZHkgYXR0cmlidXRlLg==');
controller.fileBody = v;
controller.processFile( );

(The encoded string is just the first paragraph encoded in base64).

All Answers

sfdcfoxsfdcfox

You can encode a test document as a base64 string, then hand that value to the blob object you've bound to your inputfile's body attribute.

 

Blob v = EncodingUtil.base64Decode('WW91IGNhbiBlbmNvZGUgYSB0ZXN0IGRvY3VtZW50IGFzIGEgYmFzZTY0IHN0cmluZywgdGhlbiBoYW5kIHRoYXQgdmFsdWUgdG8gdGhlIGJsb2Igb2JqZWN0IHlvdSd2ZSBib3VuZCB0byB5b3VyIGlucHV0ZmlsZSdzIGJvZHkgYXR0cmlidXRlLg==');
controller.fileBody = v;
controller.processFile( );

(The encoded string is just the first paragraph encoded in base64).

This was selected as the best answer
sfdcfoxsfdcfox

You might not have @isTest(SeeAllData=true) set on your test method, as well. That would cause your query to fail as well.

studiopikastudiopika

 

I ended up constructing a blob in the testMethod.