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
dotNetkowdotNetkow 

Unit testing with Static Resources

I have a method that I need to unit test which retrieves a Static Resource object based on the name of the file passed to the method.  In the unit test, I'd like to insert a new Static Resource, like so:

 

Blob b = Blob.valueOf('file contents here');       
StaticResource resource = new StaticResource(Body=b,Name='testFileName');       
insert resource;

// call method to test with newly created Static Resource
string result = methodToTest('testFileName');

 

 However, it fails when trying to insert the static resource.  How else can I insert it?  Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

Static resources aren't available from apex I'm afraid - they are part of the metadata api.

All Answers

bob_buzzardbob_buzzard

Static resources aren't available from apex I'm afraid - they are part of the metadata api.

This was selected as the best answer
dotNetkowdotNetkow

Ok, so there is absolutely no way to insert/create static resources via apex then? 

bob_buzzardbob_buzzard

I'm afraid not.  I've been trying to access them that way for a while now but haven't found a way though.  They are only available to visualforce pages or the metadata api (force.com ide for example).

SF1DevSF1Dev

These days, you can access static resources from Apex like so:

StaticResource sResource = [select id,body from StaticResource Where Name = 'name of static resource goes here'];
String fileContent = sResource.body.toString();