0

I have a simple Apex Class and VFPage that displays records in a print preview which I can then output to Word Doc.

It is now time to push to production. I am new to writing test scripts for code coverage.

I am having a challenge writing the test to achieve the proper code coverage. I am currently at 36%. The specific challenge I am having is testing the custom object records.

Here is the code coverage results:

enter image description here Here is the Apex Class:

public class MyVACommunityControllerExtension {

    private final MyVA_Community__c myva;

    public List content;

    // The extension constructor initializes the private member
    // variable myva by using the getRecord method from the standard
    // controller.
    public MyVACommunityControllerExtension(ApexPages.StandardController stdController) {
        this.myva = (MyVA_Community__c)stdController.getRecord();     
    }

    public PageReference records() 
    {
        return new PageReference('/apex/MyVACommunityDownload');
    }

    public list getContent()
    {
        if(content==null) {
            list cs = new list();
            for(Community_Contacts__c c : [Select c.id, c.name, contact__r.name, contact__r.title, c.contact__c, c.role__c, c.myva_community__c from community_contacts__c c WHERE c.myva_community__c = :ApexPages.currentPage().getParameters().get('Id')]){
                cs.add(c);
            }

            if(cs.size() !=0) { content=cs; }
        }
        return content;
    }           
}

Here is the Visual Force Page code:

enter image description here

Below is the Test Class:
a. I have intentionally hard-coded ID info to test the test script
b. I have included both @IsTest(SeeAllData=true) and Created my own data
c. I am struggling with how to test the query data results in my Apex Class
d. Thank you in advance for any direction you may be able to provide

/**
 * An apex page controller that generates WordDoc from data record
 */
@IsTest 
public with sharing class TestMyVACommunityControllerExtension {
    @IsTest      
    public static void testMyVACommunityControllerExtension() {
        MyVACommunityControllerExtension controller = new MyVACommunityControllerExtension(new ApexPages.StandardController(new MyVA_Community__c()));

        PageReference pageRef = controller.records();  

        //Beginning of System Asserts, verify pageRef and URL First
        System.assertNotEquals(null,pageRef);
        System.assertEquals('/apex/MyVACommunityPrintView',pageRef.getUrl());

        //Verify the pageRef parameters as well
        Map pageParameters = pageRef.getParameters();
        System.assertEquals(0,pageParameters.values().size());

        // Create and insert an account
        Account acc = new Account(name='TestClient');
        insert acc;

        //Create and insert a contact
        Contact con = new Contact(LastName = 'TestConLN', FirstName = 'TestConFN', Email='test@testing.com', AccountId=acc.Id);
        insert con;

        //Create and insert a MyVA Community
        MyVA_Community__c myva = new MyVA_Community__c (Community_Name__c = 'TestCommunity');
        insert myva;

        //Create and insert a Community Contact for MyVA Community
        Community_Contacts__c comCont = new Community_Contacts__c (MyVA_Community__c = myva.Id, Contact__c= con.Id, role__c ='Director');
        //insert comCont;
        insert comCont;


        // Perform test
        Test.startTest();
            list cs = controller.getContent();
            for(Community_Contacts__c c : [Select c.id, c.name, contact__r.name, contact__r.title, c.contact__c, c.role__c, c.myva_community__c from community_contacts__c c WHERE c.Id !=NULL]){
                cs.add(c); 
        }

        Test.stopTest();

        // Verify
        System.assertEquals(con.Name, myva.Community_Contacts__c);
    }    

    @isTest static void constructorTest() {
        // Create and insert an account
        Account acc = new Account(name='TestClient');
        insert acc;

        //Create and insert a contact
        Contact con = new Contact(LastName = 'TestConLN', FirstName = 'TestConFN', Email='test@testing.com', AccountId=acc.Id);
        insert con;

        //Create and insert a MyVA Community
        MyVA_Community__c myva = new MyVA_Community__c (Community_Name__c = 'TestCommunity');
        insert myva;

        //Create and insert a Community Contact for MyVA Community
        Community_Contacts__c comCont = new Community_Contacts__c (MyVA_Community__c = myva.Id, Contact__c= con.Id, role__c ='Director');
        //insert comCont;
        insert comCont;

        // start the test execution context
        Test.startTest();

        // set the test's page to your VF page (or pass in a PageReference)
        Test.setCurrentPage(Page.MyVACommunityPrintView);

        // call the constructor
        MyVACommunityControllerExtension controller = new MyVACommunityControllerExtension(new ApexPages.StandardController(new MyVA_Community__c()));


        // test action methods on your controller and verify the output with assertions
        //controller.save();

        // stop the test
        Test.stopTest();

        System.assertEquals('Director', comCont.role__c);
    }    

}

Here is the ControllerTest that resulted in 100% code coverage:

/**
 * An apex page controller that generates WordDoc from data record
 */
@IsTest 
public with sharing class MyVACommunityControllerExtensionTest {
    @IsTest      
    public static void MyVACommunityControllerExtensionTest() {
        MyVACommunityControllerExtension controller = new MyVACommunityControllerExtension(new ApexPages.StandardController(new MyVA_Community__c()));

        PageReference pageRef = controller.records();  

        //Beginning of System Asserts, verify pageRef and URL First
        System.assertNotEquals(null,pageRef);
        System.assertEquals('/apex/MyVACommunityPrintView',pageRef.getUrl());

        //Verify the pageRef parameters as well
        Map pageParameters = pageRef.getParameters();
        System.assertEquals(0,pageParameters.values().size());

        // Create and insert an account
        Account acc = new Account(name='TestClient');
        insert acc;

        //Create and insert a contact
        Contact con = new Contact(FirstName = 'TestConFN', LastName = 'TestConLN', Email='test@testing.com', Title='Director', AccountId=acc.Id);
        insert con;

        //Create and insert a MyVA Community
        MyVA_Community__c myva = new MyVA_Community__c 
                (Community_Name__c = 'TestCommunity', City__c = 'Los Angeles', 
                 State__c = 'CA', Name_of_Existing_Group__c = 'ExistingGroup', 
                 Georgraphy__c='geography', VA_District__c='Pacific', Milestone_2_Co_Chairs__c='In Progress',
                 Milestone_3_Board_Members__c='In Progress', Milestone_4_1st_Board_Meeting_Scheduled__c = Date.valueOf('2015-10-01'),
                 Milestone_5_1st_public_Forum_Scheduled__c= Date.valueOf('2015-11-20'), Charter__c='Yes', 
                 Collaboration__c='collaboration', State_VA_Office_Engagement__c='No', State_DVA_POC__c='theContact',
                 Next_Steps__c='These are next steps');
        insert myva;

        //Create and insert a Community Contact for MyVA Community
        Community_Contacts__c comCont = new Community_Contacts__c (MyVA_Community__c = myva.Id, Contact__c= con.Id, 
                 role__c ='VHA Board Member');

        insert comCont;

        // Verify that the success page displays
        System.assertEquals('/apex/MyVACommunityPrintView',pageRef.getUrl());
        Community_Contacts__c[] content = [Select c.id, c.name, contact__r.name, contact__r.email, contact__r.title, c.contact__c, c.role__c, c.myva_community__c from community_contacts__c c WHERE c.Id !=NULL];


        MyVACommunityControllerExtension controllerTest = new MyVACommunityControllerExtension(new ApexPages.StandardController(myva));     
        pageRef = controllerTest.records();  
        controllerTest.getContent();

        //Test.stopTest();

        // Verify
        System.assertEquals('test@testing.com', content[0].contact__r.email);
        System.assertEquals('VHA Board Member', content[0].role__c);
        System.assertEquals('TestConFN TestConLN', content[0].contact__r.name);
        System.assertEquals('Director', content[0].contact__r.title);
        System.assertEquals(content.size() !=0, true);
    }    

}
1

There are absolutely loads of questions to do with testing and code coverage on here already, so have a good search. Here's some generic help with writing tests for extensions:

Need Help for Extension Test Class

Some specific advice, though:

Do not use @IsTest(SeeAllData=true) unless you really, really, really have to. I've used it just once in the past year: where I added a trigger to a managed package with such a crazy-complicated object structure that I couldn't create my own test data inside the test, even after hours of effort. You are already creating your own test data, so you shouldn't need it. In fact, it can be a problem because duplicate detection might one day stop your test data from inserting if someone creates a record with the email 'test@testing.com'.

Call your getContent() method in the test. You haven't provided your VF code, but I guess you call it inside an <apex:repeat> or a table, or something. When you run the test, it doesn't really execute your VF, so you need to call that method explicitly in your test. Where you have this:

        list cs = new list();
        for(Community_Contacts__c c : [Select c.id, c.name, contact__r.name, contact__r.title, c.contact__c, c.role__c, c.myva_community__c from community_contacts__c c WHERE c.contact__c = '003r0000002Kz6bAAC']){
                cs.add(c); 
        }    

You should, instead use this:

list cs = controller.getContent();

Then, assert that cs contains the things that you expected.

You can "call" your VF page like this:

// set the test's page to your VF page (or pass in a PageReference)
Test.setCurrentPage(Page.WhateverYourPageIsNamed);

Although it doesn't really do very much, except allowing any code that gets the current page to know where it is.

  • thank you for the direction. I have cleaned up the code, however, i am getting an error message at "cs.add(c)" System.NullPointerException: Attempt to de-reference a null object. I am also not sure how I call the VF page. I do already include: System.assertEquals('/apex/MyVACommunityPrintView',pageRef.getUrl()); – tomc0920 Nov 5 '15 at 11:13
  • I added how to call the VF page to my answer. Your NullPointerException looks to me like a genuine bug... getContent() returns content, but never sets it to have a value. So it returns null. I guess you should be writing content = new list(); ... content.add(c); instead of list cs = new list();... cs.add(c); – Aidan Nov 5 '15 at 13:01
  • thank you! everything is compiling nicely, test data is being created and values are being asserted. I'm still struggling with code coverage at 36%. – tomc0920 Nov 5 '15 at 23:38
  • Maybe post up your revised code? – Aidan Nov 6 '15 at 10:17

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.