Document folders be created in unit tests? If not, is there a simple workaround for testing
Document objects in unit tests?
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.
I'm using the following code as a workaround:
Document document = new Document(); document.AuthorId = UserInfo.getUserId(); document.FolderId = UserInfo.getUserId();
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().
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;