+ Start a Discussion

Creating test Folder object with DML

Hi All,

Is there a way around the error 'DML not supported for Folder' in a testMethod? This is being a real problem for me because it's preventing me from getting the 75% coverage I need for this class.

One thing I tried is using test code that tries to find one existing Folder object and using that. Like this:

        Folder[] folder = [SELECT Id FROM Folder LIMIT 1];

This works in development, but when I install the package that this code belongs to, I get this error mesage, and the install fails:

System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: FolderId (invalid folder): [FolderId]

Any help would be appreciated.



This is now more of a problem, with the Spring 12 release (API version 24), the default is to not see existing folders. So there are times I need a document or emailtemplate folder, but I cannot create one, nor can I see one, unless I set the "SeeAllData=true" on each test or test class.



sandeep kumar 44sandeep kumar 44
Hello Andrew,

i am getting the same error in my test class do you fix it ? i so can you please share the solution with me 

Hi, I posted this a long time ago... I don’t remember getting a resolution Andrew
sandeep kumar 44sandeep kumar 44
Hello Andrew,

i fixed it . atually what you need to do is pass UserInfo.getUserId() for folderid while creating document. 

Document doc = new Document(FolderId = UserInfo.getUserId() ,Name='mySampleFile', Body = Blob.ValueOf('Hello World'));
    insert doc;

and this will work 
Sandeep, that is an interesting workaround, and it does indeed work.  

The reason for the error above though is the fact that the query is pulling in a folder that is not of type "Document", but is probably of type "Report" or "Dashboard", and those cannot be used for attaching documents, hence, the error.  So another solution for the original problem is to modify the query as follows:

Folder[] folder = [SELECT Id FROM Folder where Type = 'Document' LIMIT 1];

I tested both solutions and they both work.
Jap Hendy WijayaJap Hendy Wijaya
ok i'm new to salesforce, but @sandeep kumar 44 solution still work. But i'm still curios why SF can't just use another folder. Thank you sandeep, this help very much on my projet