15

Can Document folders be created in unit tests? If not, is there a simple workaround for testing Document objects in unit tests?

2

Unfortunately most metadata objects, such as Folders, don't support DML and are only available for programmatic manipulation via the Metadata API which means you're stuck with the folders already in the org when you run your test.

One approach is create a specific folder for testing and use that in your tests. Alternatively you can query a folder for use in your tests.

13

I'm using the following code as a workaround:

Document document = new Document();
document.AuthorId = UserInfo.getUserId();
document.FolderId = UserInfo.getUserId();
  • AuthorId isn't strictly necessary. My Document will insert just fine when setting only Body, FolderId, and Name – Nathan Wallace Oct 8 '13 at 19:05
7

The FolderId lookup on Document is actually a polymorphic field that can lookup to a Folder or a User (so that document will added the My Personal Documents folder), so in your unit tests you can just set the FolderId to UserInfo.getUserId().

0

According to the Object Reference, the following calls are supported for folders: create(), delete(), describeSObjects(), getDeleted(), getUpdated(), query(), retrieve(), update(), upsert(), so it appears to me that they can be created! According to the docs, only one type of item can be contained in a folder.

I just tried creating one in the Dev Console and got a message back saying ': DML not allowed on Folder'. Might still work in a test method, but it didn't work as anonymous code using what's below:

Folder f = New Folder(name = 'MyDocuments', Type='Document');
Insert f;
  • You cannot use DML for Folders in test methods. – ipavlic Jun 5 '13 at 8:20
  • Thanks for letting us know it didn't work in a test method either! – crmprogdev Jun 5 '13 at 13:46
  • @ipavlic So how we can create test data for folder – Pravesh Mehta Jan 27 '16 at 8:21
  • I would import it from a static resource if it can't be created. – crmprogdev Jan 27 '16 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.