+ Start a Discussion
Holly Havelka 10Holly Havelka 10 

Help Getting Test Code Coverage Higher

Hi all,

I am still learning on writing my test code coverage.  I would like to get as close to 100% as possible with the below test class.  Any suggestions on what I could add to get the test code coverage higher?  It's currently at 77%.

Thanks in advance for your feedback.

Controller:
global class CustomLoginController {

    /*Initialization*/
    
    global CustomLoginController () {

    List<Breakthrough_Application_Settings__c> settings = [select Display__c,
                Application_Open__c,
                Regular_Deadline__c,
                Backdoor_Application_Open__c,
                Name 
              from Breakthrough_Application_Settings__c 
              where Active__c = true LIMIT 1];
        if (settings.size() > 0) {
        Datetime regAppOpen = Datetime.newInstance(settings[0].Application_Open__c, Time.newInstance(0,0,0,0));
        Datetime backdoorOpen = Datetime.newInstance(settings[0].Backdoor_Application_Open__c, Time.newInstance(0,0,0,0));
        Datetime regularDeadline = Datetime.newInstance(settings[0].Regular_Deadline__c, Time.newInstance(0,0,0,0)).addDays(1);
        this.regularApplicationOpen = Datetime.now() >= regAppOpen;
        this.backdoorApplicationOpen = Datetime.now() >= backdoorOpen;
        this.isRegularDeadlineReach = Datetime.now() >= regularDeadline;
        this.isDisplayed = settings[0].Display__c;
        }
    }
    
    /*End Initialization*/
    
    /*Properties*/
    
    global String username{get;set;}
    global String password{get;set;}
    
    global String firstName {get; set;}
    global String lastName {get; set;}
    global String email {get; set;}
    global String createPassword {get; set {password = value == null ? value : value.trim(); } }
    global String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
    global String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }

    public Breakthrough_Application_Settings__c settings { get; set; }
    public Boolean isDisplayed { get; set; }
    public Boolean backdoorApplicationOpen { get; set; }
    public Boolean regularApplicationOpen { get; set; }
    public Boolean isRegularDeadlineReach { get; set; }

    /*End Properties*/
    
    /*Action Methods*/
    
    global PageReference forwardToCustomAuthPage() {
        return new PageReference( '/CustomLogin');
    }
    
    global PageReference login() {
    
    
        return Site.login(username, password, null);
    }
    
    private boolean isValidPassword() {
        return password == confirmPassword;
    }
    
    @TestVisible
    private Id accountId;
    private String emailAddress;
    
    global PageReference registerUser() {
        Breakthrough_Application_Login_Settings__c settings = Breakthrough_Application_Login_Settings__c.getOrgDefaults();
        // it's okay if password is null - we'll send the user a random password in that case
        if (!isValidPassword()) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
            ApexPages.addMessage(msg);
            return null;
        }
        
        //String profileId = UserUtils.getAlumniCommunityProfileId();
        String profileId = settings.ProfileId__c;      
        String roleEnum = null; // To be filled in by customer.
        
        String userName = email;
        
        // Get the email address from the Custom Setting
        emailAddress = BCUtils.getDefaultAlumniDirectoryEmail();
        
        String baseURL = BCUtils.getDefaultAlumniDirectoryBaseURL();
        
        Boolean sendEmail = false;
        String subject = '';
        String htmlBody = '';
        
        // Create a savepoint while AccountNumber is null
        Savepoint sp = null;
        Contact contact;
        // BC-20 match portal user to existing SFDC contact that belongs in a portal enabled account
        List<Contact> contacts = [select Id, AccountId from Contact where Email = :email and Account.IsPartner = true];
        if (contacts.size() == 0) {
            
            // Case 1, 2c, 3c
            
            // no existing contact: let SFDC create a new contact under the default Alumni Community account
           // accountId = AccountUtils.getAlumniCommunityAccountId();
            accountId = settings.AccountId__c;
            // Create a savepoint before the contact is created
            sp = Database.setSavepoint();
            
            // Create the contact with the Default account Id
            //Contact c = ContactUtils.createContact(firstName, lastName, email, accountId, RecordTypes.contactAlumniTypeId, true);
            contact = new Contact(
              FirstName = firstName,
              LastName = lastName,
              Email = email,
              AccountId = accountId,
              RecordTypeId = RecordTypes.contactAlumniTypeId,
              OwnerId = settings.OwnerId__c
          );
          insert contact;
            
            
            
            // Send email address to Breakthrough staff letting them know that a new Portal User has been created.
            if(emailAddress != null)
            {
                sendEmail = true;
                subject = 'New portal user lacking valid existing contact';
                htmlBody = 'A new user has registered for the portal without having an existing contact or having a contact that is not associated with a portal enabled account.<br/><br/><a href="' + baseUrl + '/' + contact.Id + '">' + firstName + ' ' + lastName + '</a>';
            }
           
        } else if (contacts.size() >= 1) {
            
            List<User> userList = [Select Id from user where ContactId IN :contacts and ProfileId = :profileId and (UserType = 'PowerPartner' or UserType = 'Partner')];
            
            if(!userList.isEmpty())
            {
                // Case 2a, 3a
                
                // a user already exists for this contact: display an error
                ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,
                'You already have a Portal account. Please contact Breakthrough Collaborative if this is in error.');
                ApexPages.addMessage(msg);
                return null;
            }
            
            // Case 2b, 3b - match one unique existing contact: let SFDC use this contact
            accountId = contacts[0].AccountId;
            contact = contacts[0];
            if(contacts.size() > 1 && emailAddress != null)
            {
                // Send email address to Breakthrough staff letting them know that a new Portal User has been created.
                sendEmail = true;
                
                subject = 'New portal user has multiple matching contacts';
                htmlBody = 'A new user has registered for the portal while having multiple contacts; they have been matched to one.<a href="' + baseUrl + '/' + contacts[0].Id + '">' + firstName + ' ' + lastName + '</a>';
                
            }
        }
        
        //Role role = [Select Id from Role where Id = '00Ee0000000NP3SEAW'];
        
        User u = new User();
        u.Username = userName;
        u.Email = email;
        u.FirstName = firstName;
        u.LastName = lastName;
        //u.CommunityNickname = communityNickname;
        u.communityNickname = generateNickname(firstName, lastName);
        u.ProfileId = profileId;
        //u.ReceivesInfoEmails = true;
        u.UserPermissionsSFContentUser = true;
        u.ContactId = contact.Id;
        
        String userId = null;
        
        try{
            userId = Site.createPortalUser(u, accountId, password);
        }
        catch(Exception e)
        {
            // Rollback to before the contact was created
            if(sp != null)
                Database.rollback(sp);
            
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR,
                e.getMessage());
            ApexPages.addMessage(msg);
            return null;
        }
        
        if (userId != null) {
            
            if(sendEmail)
                CommonUtils.sendEmail(new String[]{emailAddress}, emailAddress, 'Alumni Directory', subject, htmlBody);
            
            if (password != null && password.length() > 1) {
                return Site.login(userName, password, ApexPages.currentPage().getParameters().get('startURL'));
            }
            else {
                PageReference page = System.Page.CommunitiesSelfRegConfirm;
                page.setRedirect(true);
                return page;
            }
        }
        else
        {
            // Rollback to before the contact was created
            if(sp != null)
                Database.rollback(sp);
        }
        
        return null;
    }
    
    /*End Action Methods*/
    
    /*Helper Methods*/
    
    private String generateNickname(String firstName, String lastName)
    {
        String communityNickname = '';
        
        if(firstName != null && firstName != '')
            communityNickname += firstName.substring(0, 1);
        
        communityNickname += lastName + CommonUtils.getCurrentTimeMillis();
        
        return communityNickname;
    }
    
    /*End Helper Methods*/
}

Test Code Class:
@isTest
public class CustomLoginControllerTest {
    @IsTest(SeeAllData=true)
    public static void testCommunitiesSelfRegController() {
        
        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;

        Test.startTest();

        CustomLoginController controller = new CustomLoginController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@force.com';
        controller.communityNickname = 'test';
        
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null);
        
        controller.createPassword = 'abcd1234';
        controller.confirmPassword = 'abcd123';
        System.assert(controller.registerUser() == null);

        System.assertEquals(true, controller.backdoorApplicationOpen);
        System.assertEquals(true, controller.regularApplicationOpen);
        System.assertEquals(true, controller.isRegularDeadlineReach);
        System.assertEquals(false, controller.isDisplayed);

        Test.stopTest();
    }
    
    @isTest
    public static void userWithNoMatchingContactCreatedUnderDefaultAccount() {

        BCUtils.createAlumniDirectorySettings('Default Portal Account', 'resumeUrl', true);

        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;
        
        Account a1 = AccountUtils.createBreakthroughOrgAccount('Default Portal Account', false);
        Account a2 = AccountUtils.createBreakthroughOrgAccount('Another Portal Account', false);
        List<Account> accounts = new List<Account> { a1, a2 };
        insert accounts;
        a1.isPartner = true;
        a2.isPartner = true;
        update accounts;
        Breakthrough_Application_Login_Settings__c settings = new Breakthrough_Application_Login_Settings__c();
        settings.OwnerId__c = UserInfo.getUserId();
        settings.AccountId__c = a1.Id;
        insert settings;
        Test.startTest();
        
        CustomLoginController controller = new CustomLoginController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@alumni.test';
        controller.communityNickname = 'test';
        
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null);
        
        System.assertEquals(a1.Id, controller.accountId);
        System.assertEquals(false, ApexPages.hasMessages());
        
        System.assertEquals(false, controller.backdoorApplicationOpen);
        System.assertEquals(true, controller.regularApplicationOpen);
        System.assertEquals(false, controller.isRegularDeadlineReach);
        System.assertEquals(true, controller.isDisplayed);
        
        Test.stopTest();
    }
    
    @isTest
    public static void userWithOneMatchingContactCreatedUnderMatchedAccount() {
        BCUtils.createAlumniDirectorySettings('Default Portal Account', 'resumeUrl', true);

        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;
        
        Account a1 = AccountUtils.createBreakthroughOrgAccount('Default Portal Account', false);
        Account a2 = AccountUtils.createBreakthroughOrgAccount('Another Portal Account', false);
        List<Account> accounts = new List<Account> { a1, a2 };
        insert accounts;
        a1.isPartner = true;
        a2.isPartner = true;
        update accounts;
        
        Contact c = ContactUtils.createAlumniContact('Test', 'Alumni', 'test@alumni.test', a2.Id, true);
        
        Test.startTest();
        
        CustomLoginController controller = new CustomLoginController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@alumni.test';
        controller.communityNickname = 'test';
        
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null);
        
        System.assertEquals(a2.Id, controller.accountId);
        System.assertEquals(false, ApexPages.hasMessages());

        System.assertEquals(false, controller.backdoorApplicationOpen);
        System.assertEquals(true, controller.regularApplicationOpen);
        System.assertEquals(false, controller.isRegularDeadlineReach);
        System.assertEquals(true, controller.isDisplayed);
        
        Test.stopTest();
    }
    
    @isTest
    public static void userWithMultipleMatchingContactCreated() {
        BCUtils.createAlumniDirectorySettings('Default Portal Account', 'resumeUrl', true);

        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;
        
        Account a1 = AccountUtils.createBreakthroughOrgAccount('Default Portal Account', false);
        Account a2 = AccountUtils.createBreakthroughOrgAccount('Another Portal Account', false);
        List<Account> accounts = new List<Account> { a1, a2 };
        insert accounts;
        a1.isPartner = true;
        a2.isPartner = true;
        update accounts;
        
        Contact c1 = ContactUtils.createAlumniContact('Test', 'Alumni', 'test@alumni.test', a1.Id, true);
        Contact c2 = ContactUtils.createAlumniContact('Test', 'Alumni', 'test@alumni.test', a2.Id, true);
        
        Test.startTest();
        
        CustomLoginController controller = new CustomLoginController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@alumni.test';
        controller.communityNickname = 'test';
        
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null);
        
        System.assertNotEquals(null, controller.accountId);
        System.assertEquals(false, ApexPages.hasMessages());
        
        System.assertEquals(false, controller.backdoorApplicationOpen);
        System.assertEquals(true, controller.regularApplicationOpen);
        System.assertEquals(false, controller.isRegularDeadlineReach);
        System.assertEquals(true, controller.isDisplayed);

        Test.stopTest();
    }

    @isTest
    public static void CustomAuthPage() {
        BCUtils.createAlumniDirectorySettings('Default Portal Account', 'resumeUrl', true);

        Breakthrough_Application_Settings__c setting = new Breakthrough_Application_Settings__c();
        setting.Name = '2015';
        setting.Active__c = true;
        setting.Application_Open__c = Date.today().addDays(-20);
        setting.Regular_Deadline__c = Date.today();
        setting.Backdoor_Application_Open__c = Date.today().addDays(2);
        setting.Display__c = true;
        insert setting;

        PageReference ref = new PageReference('/apex/CustomLogin');
        Test.setCurrentPage(ref);
        CustomLoginController controller = new CustomLoginController();

        Test.startTest();
            ref = controller.forwardToCustomAuthPage();
        Test.stopTest();
        system.assertEquals('/CustomLogin', ref.getUrl());
    }
}

 
Best Answer chosen by Holly Havelka 10
Alain CabonAlain Cabon
Don't forget to clearly indicate the lines of code that aren't covered.

Checking Code Coverage: 

You can view code coverage in several places in the Developer Console.

To view line-by-line code coverage for an Apex class, open the class. The Code Coverage menu (upper left) will include one or more of the following options depending on the tests you have implemented:
  • None
  • All Tests: The percentage of code coverage from all test runs.
  • className.methodName: The percentage of code coverage from a method executed during a test run.
Lines of code that are covered by tests are blue. Lines of code that aren’t covered are red. Lines of code that don’t require coverage (for example, curly brackets, comments, and System.debugcalls) are left white.

https://help.salesforce.com/articleView?id=code_dev_console_tests_coverage.htm&type=0