0

Having a bit of difficulty getting any code coverage for my custom controller. The goal of the controller is to display a list of opportunities in a list where the division of the user is the same as the division on the opportunity. This is my first go at custom controllers and VF pages.

Controller

public class PrnlDueCon {

    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                    [SELECT Name, Policy_Type__c, StageName, closeDate, KBI_DivisionOPP__c, Income__c  FROM Opportunity 
                     WHERE (closeDate <= NEXT_90_DAYS) AND (StageName = 'Pre-Renewal To Be Sent')
                     AND (Type = 'Existing Customer - Renewal')]));
            }
            return setCon;
        }
        set;
    }

    public List<Opportunity> getOpportunities() {
        List<User> UserListDiv = [SELECT Division FROM User WHERE Id = :UserInfo.getUserId() LIMIT 1];
        string UserDiv = string.valueOf(UserListDiv[0].Division);
        List<Opportunity> OppsToDisplay = new List<Opportunity>();

        List<Opportunity> AllRenewals = setCon.getRecords();

        For (Opportunity Rnl : AllRenewals) {
            if(Rnl.KBI_DivisionOPP__c == UserDiv) {
                OppsToDisplay.add(Rnl);
            }                
        }
    return OppsToDisplay;          
    }       
}

VF Page

<apex:page controller="PrnlDueCon" lightningStyleSheets="true">
    <apex:pageBlock >
        <apex:pageBlockTable value="{!opportunities}" var="o">
            <apex:column headerValue="NAME">
                <apex:outputlink value="/{!o.Id}">{!o.Name}</apex:outputlink>
            </apex:column>
            <apex:column value="{!o.Income__c}"/>            
            <apex:column value="{!o.CloseDate}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>   
</apex:page>

Test Class

@isTest
public class PrnlDueConTEST {
    public static testMethod void createAccAndOpp() {

        Test.startTest();

        // Create Role

        UserRole r = new UserRole(DeveloperName = 'MyCustomRole', Name = 'My Role');
        insert r;


        // Create User

        User newUser = new User();

        newUser.ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].id;
        newUser.LastName = 'test';
        newUSer.Email = 'test@test.com';     
        newUser.Username = 'test@test.com' + system.currentTimeMillis();
        newUser.CompanyName = 'TESTCO';
        newUSer.Title = 'Title';        
        newUser.Alias = 'alias';
        newUser.TimeZoneSidKey = 'America/Los_Angeles';
        newUSer.EmailEncodingKey = 'UTF-8';
        newUSer.LanguageLocaleKey = 'en_US';
        newUSer.LocaleSidKey = 'en_US';
        newUSer.UserRoleId = r.id;
        newUser.Division = 'Complex';

        insert newUser;


        // Create account

        system.runAs(newUser) {

            Id accRecordId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Client').getRecordTypeId();

            Account newAcc = new Account();

            newAcc.Name = 'test account';
            newAcc.KBI_Area__c = 'Complex';
            newAcc.RecordTypeId = accRecordId;
            newAcc.Account_Origin__c = 'Client Referral';

            insert newAcc;

            Id oppRecordId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Renewal').getRecordTypeId();


            // Create Opportunity

            List<Opportunity> OppList = new List<Opportunity>();

            Opportunity newOpp = new Opportunity();

            newOpp.Name                         = 'Test Name Opp';
            newOpp.KBI_DivisionOPP__c           = 'Complex';
            newOpp.AccountID                    = newAcc.id;
            newOpp.RecordTypeId                 = oppRecordId;
            newOpp.Income__c                    = 1;
            newOpp.Type                         = 'Existing Customer - Renewal';
            newOpp.StageName                    = 'Pre-Renewal To Be Sent';
            newOpp.Policy_Type__c               = 'Boat';
            newOpp.CloseDate                    = date.today() + 10;

            OppList.add(newOpp);

            insert OppList;

            PageReference ref = Page.PrnlDueVFP;                       

            PrnlDueCon TestPrnlTestCon = new PrnlDueCon();

            test.stopTest();       
        }              
    }
}
  • Your unit test does not invoke your controller, save its constructor. Fundamentally, testing a Visualforce controller is not much different from testing other Apex code - you must invoke each code path in test context in order to validate its behavior and gain the side effect of code coverage. – David Reed Jan 7 '19 at 2:57
  • Brilliant, thanks David. I added TestPrnlTestCon.getOpportunities(); and are now achieving 100% code coverage – Daniel Jan 7 '19 at 3:34
  • I'd encourage looking at some of our unit test resources. Your unit tests currently are making no assertions, and hence don't validate your code's behavior. – David Reed Jan 7 '19 at 3:39
0

Your test class need to be updated. Add the below lines before test.stopTest(); and run test.

PrnlDueCon TestPrnlTestCon = new PrnlDueCon();
System.assert(TestPrnlTestCon.setCon != null);
System.assert(TestPrnlTestCon.getOpportunities() != null);

Please go through Apex testing trailhead module and understand how to assert and validate your code.

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.