The code as written below uploads a file to salesforce, then redirects the user to a specific page.

public class ContentController {

    public contentController() {
        file = new ContentVersion();

    public ContentVersion file { get; set; }
    public PageReference go() {
        insert file;

        return new PageReference('** an example url**');

How can I write an automated unit test to test "uploading a file"? I don't quite get how to do so unless I somehow generate an anonymous file in apex which only works with documents, but not all file types.

1 Answer 1


You just need to query the data to make sure it actually gets into the database. You should also test on the redirect.

MyController controller = new MyController();
controller.file.Body = Blob.valueOf('populated');

    PageReference redirect = MyController.go();

system.assertEquals(1, [SELECT count() FROM ContentVersion]);
// assert on redirect

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.