Sorry I am new with salesforce developer. I have written method for extension controller. I need help with writing test class for that method. with that method what it does is visualforce is renderas pdf and that visualforce is gets attach to files related object for that account.

<public pageReference savePDF(){
    if(doSave == 'No'){ return null; }
     PageReference pagePdf = new PageReference('/apex/BAR_ctrl_Test');
     pagePdf.getParameters().put('id', acct.Id);
     pagePdf.getParameters().put('doSave', 'No');
     Blob pdfPageBlob;
     pdfPageBlob = pagePdf.getContentAsPDF();
     Date d = Date.Today() ;
     String dateStr =  d.format() ;
    List<ContentDocumentLink> docList = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :acct.Id];

    Set<Id> CDLs = new Set<Id>();
    for (ContentDocumentLink docLink : docList) {
    string onepage='One Pager '+dateStr;

    List<ContentVersion> files = [SELECT Id, Title, ContentDocument.Id, ContentDocument.ContentSize, ContentDocument.FileType, ContentDocument.Description
                                  FROM ContentVersion 
                                  WHERE ContentDocumentId IN :CDLs and Title like :onepage ];       
    // Create Document into PDF
     ContentVersion  a = new ContentVersion();
     a.versionData = pdfPageBlob;
     a.ContentLocation = 'S';
     a.Title = 'One Pager '+dateStr;
     a.PathOnClient = '/acct.id.pdf';
     a.isMajorVersion= false;       
        insert a;
        ContentVersion acctContent = [SELECT id,FirstPublishLocationId, ContentDocumentId,title FROM ContentVersion where Id = :a.Id];
        ContentDocumentLink contentlink=new ContentDocumentLink();
        contentlink.LinkedEntityId= acct.id;
        contentlink.ShareType= 'V';
        insert contentlink;  
        for(ContentVersion k: files){
            k.versionData = pdfPageBlob;
            k.Title = 'One Pager '+dateStr;
        update files;
     return null;

closed as unclear what you're asking by David Reed, glls, Sebastian Kessel, Oleksandr Berehovskyi, Derek F Aug 28 '18 at 13:00

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    Hello Rahul, welcome to SFSE. Code coverage is one of the most common questions we receive. Have you had a chance to complete the Trailhead module on this subject, review any of the 3,000+ existing questions on unit tests, or review resources like the Salesforce Developer Blog or How to Write Good Unit Tests? – David Reed Aug 28 '18 at 0:02
  • 2
    Please be aware that SFSE is not a code-writing service, and your questions need to meet some expectations about specificity, detail, and showing your own work. – David Reed Aug 28 '18 at 0:03
  • Yes. I have complete it but I have never work with contentversion and contentdocument before. So that is why i needed help. for writing test class for it. – Rahul Patel Aug 28 '18 at 0:45

At least 75% of your Apex code must be covered by unit tests, and all of those tests must complete successfully. Note the following. When deploying Apex to a production organization, each unit test in your organization namespace is executed by default. Calls to System.debug are not counted as part of Apex code coverage. Test methods and test classes are not counted as part of Apex code coverage. While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered. Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well as bulk and single records. This should lead to 75% or more of your code being covered by unit tests. Every trigger must have some test coverage. All classes and triggers must compile successfully.

Best practise:-

  1. If code uses conditional logic (including ternary operators), execute each branch.
  2. Make calls to methods using both valid and invalid inputs.
  3. Complete successfully without throwing any exceptions, unless those errors are expected and caught in a try…catch block.
  4. Always handle all exceptions that are caught, instead of merely catching the exceptions.
  5. Use System.assert methods to prove that code behaves properly.
  6. Use the runAs method to test your application in different user contexts.
  7. Exercise bulk trigger functionality—use at least 20 records in your tests.
  8. Use the ORDER BY keywords to ensure that the records are returned in the expected order.
  9. Not assume that record IDs are in sequential order.
  10. Set up test data:
  11. Create the necessary data in test classes, so the tests do not have to rely on data in a particular organization.
  12. Create all test data before calling the Test.startTest method.
  13. Since tests don't commit, you won't need to delete any data.
  14. Write comments stating not only what is supposed to be tested, but the assumptions the tester made about the data, the expected outcome, and so on. Test the classes in your application individually. Never test your entire application in a single test.

I am just giving an overview so that you can understand:-

Step 1-> You need to create a test class with @isTest annotation

public class TestDataFactory {
    public static void createTestRecords() {

step 2--> Now you need to create the Test data in inside your test method. Also, You should create a user and run your test in that user context.

String uniqueUserName = 'standarduser' + DateTime.now().getTime() + '@testorg.com';
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(Alias = 'standt', Email='standarduser@testorg.com',
        EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',
        LocaleSidKey='en_US', ProfileId = p.Id,

System.runAs(u) {
        Account acc = new Account(Name='TestAccount');
        insert acc;

        ContentVersion  a = new ContentVersion();
             a.versionData = blob.valueof('testdata');
             a.ContentLocation = 'S';
             a.Title = 'OnePage';
             a.PathOnClient = 'OnePage.pdf';
        insert a;

        ContentVersion cv=[select id, ContentDocumentId from ContentVersion where id=:a.id];

        ContentDocumentLink contentlink=new ContentDocumentLink();
                contentlink.LinkedEntityId= acc.id;
                contentlink.ShareType= 'V';
                insert contentlink; 

your apex class is used as an extension of the Visualforce page, You can write inside Test.startTest() and Test.stopTest():-

PageReference pageRef = Page.yourpage;
yourClassName objCtrl = new yourClassName();

Hope it helps you.

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