+ Start a Discussion
jagadeep kjagadeep k 

how to increase code coverage to more than 80% for my Apex class

public class lmiController {
    //Get User's Role
    public Boolean isASM{get;set;}
    public Boolean isPDM{get;set;}
    public Boolean isAssocPDM{get;set;}
    public Boolean isASR{get;set;}
    public Boolean isISR{get;set;}
    public Boolean isManager{get;set;}
    /*public PostalCodeWrapper[] cityList{get;set;}
    public ListingWrapper[] listings{get;set;}*/
    public Decimal totalPop{get;set;}
    public Decimal websiteVisits{get;set;}
    public Decimal avgCycles{get;set;}
    public Integer accountTotal{get;set;}
    public String jsonStr{get;set;}
    public Transient String availableCities{get;set;}
    public Transient String availableCounties{get;set;}
    public String selectedCities{get;set;}
    public String selectedCitiesFromCounty{get;set;}
    public Transient Postal_Code__c[] fullPostalCodes{get;set;}
    public Transient Set<Id> pcIds{get;set;}
    public Boolean disableAddAll{get;set;}
    public Boolean autoLoad{get;set;}
    //Get url hacked user's first and last name
    //public List<User> userFirstName{get;set;}
    //public List<User> userLastName{get;set;}
    //If user has employees, list here
    public List<User> employeeList {set;get;}
    public static Map<String, String> canadaStateMap = new Map<String, String>{
        'Alberta' => 'AB',
        'British Columbia' => 'BC',
        'Manitoba' => 'MB',
        'New Brunswick' => 'NB',
        'Newfoundland and Labrodor' => 'NL',
        'Nova Scotia' => 'NS',
        'Northwest Territories' => 'NT',
        'Nunavut' => 'NU',
        'Ontario' => 'ON',
        'Prince Edward Island' => 'PE',
        'Quebec' => 'QC',
        'Saskatchewan' => 'SK',
        'Yukon' => 'YT',
        'AB' => 'AB',
        'BC' => 'BC',
        'MB' => 'MB',
        'NB' => 'NB',
        'NL' => 'NL',
        'NS' => 'NS',
        'NT' => 'NT',
        'NU' => 'NU',
        'ON' => 'ON',
        'PE' => 'PE',
        'QC' => 'QC',
        'SK' => 'SK',
        'YT' => 'YT'
    };

    public static Map<String, String> canadaStateMapReversed = new Map<String, String>{
        'AB' => 'Alberta',
        'BC' => 'British Columbia',
        'MB' => 'Manitoba',
        'NB' => 'New Brunswick',
        'NL' => 'Newfoundland and Labrodor',
        'NS' => 'Nova Scotia',
        'NT' => 'Northwest Territories',
        'NU' => 'Nunavut',
        'ON' => 'Ontario',
        'PE' => 'Prince Edward Island',
        'QC' => 'Quebec',
        'SK' => 'Saskatchewan',
        'YT' => 'Yukon'
    };

    
    
    //Count number of cities
    public Integer cityCount{get;set;}
    //public Integer pagination{get;set;}
    
    public String toolUserId{get;set;}
    public List<User> userFirstLastName{get;set;} 

    public Set<String> stateFilters = new Set<String>{'CO', 'WY', 'MT', 'ID', 'WA', 'OR', 'UT', 'NV', 'CA', 'AK','HI', 'TX', 'OK', 'NM', 'AZ', 'IA', 'KS', 'NE', 'SD', 'ND',
                                                        'OH', 'IN', 'MI', 'IL', 'MO', 'WI', 'MN', 'PA', 'ME', 'MA', 'RI', 'CT', 'NH', 'VT', 'DE', 'MD', 'NY', 'NJ', 'WV', 'VA', 
                                                        'KY', 'TN', 'NC', 'SC', 'GA', 'MS', 'AR', 'LA', 'AL', 'FL', 'DC', 'PR'};

    public Set<String> canadaStateFilters = new Set<String>{'Alberta', 'AB','British Columbia', 'BC','Manitoba', 'MB','New Brunswick', 'NB','Newfoundland and Labrodor',
                                                            'NL','Nova Scotia', 'NS','Northwest Territories', 'NT','Nunavut', 'NU','Ontario', 'ON','Prince Edward Island',
                                                            'PE','Quebec', 'QC','Saskatchewan', 'SK','Yukon', 'YT'};
    //Regions:  
    //Northeast:  ME, MA, RI, CT, NH, VT, NY, PA, NJ, DE, MD
    //Southeast:  WV, VA, KY, TN, NC, SC, GA, AL, MS, AR, LA, FL
    //Midwest:  OH, IN, MI, IL, MO, WI, MN, IA, KS, NE, SD, ND
    //Southwest:  TX, OK, NM, AZ
    //West:  CO, WY, MT, ID, WA, OR, UT, NV, CA, AK, HI
    
    public void cityResults(){
        disableAddAll = false;
        selectedCities = '';
        toolUserId = ApexPages.CurrentPage().getParameters().get('id');
        autoLoad = ApexPages.currentPage().getParameters().get('autoLoad') == 'true';
        if (toolUserId == null) {
            toolUserId = UserInfo.getUserid();
        }
        
        userFirstLastName = [select FirstName, LastName from User where id = :toolUserId LIMIT 1];
        employeeList = [SELECT Id,FirstName,LastName from User WHERE isActive = true AND ManagerId = :toolUserId];

        if (!employeeList.isEmpty()) {
            isManager = true;
        }

        /*cityList = new PostalCodeWrapper[]{};
        listings = new ListingWrapper[]{};*/

        fullPostalCodes = new Postal_Code__c[]{};
        Locator_Listing__c[] fullListings;

        //If user is an ASM
        fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Area_Sales_Manager__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
        if(!fullPostalCodes.isEmpty()) {
            isASM = true;
            isASR = false;
            isPDM = false;
            isAssocPDM = false;
            isISR = false;
        } else {
            isASM = false;
        }
        
        //If user is an ASR
        if(fullPostalCodes.isEmpty()){
            fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Area_Sales_Rep__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
            if(!fullPostalCodes.isEmpty()) {
                isASM = false;
                isASR = true;
                isPDM = false;
                isAssocPDM = false;
                isISR = false;
            } else {
                isASR = false;
            }
        }
        
        //If user is a PDM
        if(fullPostalCodes.isEmpty()){
            fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Practice_Development_Manager__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
            if(!fullPostalCodes.isEmpty()) {
                isASM = false;
                isASR = false;
                isPDM = true;
                isAssocPDM = false;
                isISR = false;
            } else {
                isPDM = false;
            }
        }
        
        //If user is a PDM Associate
        if(fullPostalCodes.isEmpty()){
            fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Level_1_Practice_Development_Manager__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
            if(!fullPostalCodes.isEmpty()) {
                isASM = false;
                isASR = false;
                isPDM = false;
                isAssocPDM = true;
                isISR = false;
            } else {
                isAssocPDM = false;
            }
        }
        
        //If user is a ISR
        if(fullPostalCodes.isEmpty()){
            fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE Inside_Sales_Rep__c = : toolUserId AND ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
            if(!fullPostalCodes.isEmpty()) {
                isASM = false;
                isASR = false;
                isPDM = false;
                isAssocPDM = false;
                isISR = true;
            } else {
                isISR = false;
            }
        }

        if(fullPostalCodes.isEmpty()){
            disableAddAll = true;
            fullPostalCodes = [SELECT County__c, Avg_Monthly_Cycles_per_Territory__c,Area_Sales_Manager__c,Inside_Sales_Rep__c,Practice_Development_Manager__c,Area_Sales_Rep__c,Level_1_Practice_Development_Manager__c,Country_Name__c,City__c,State_Province__c,Name,X2020_CS_Website_Visitors__c,X2010_Census_Population__c FROM Postal_Code__c WHERE ((Country_Name__c = 'United States America' AND State_Province__c IN :stateFilters) OR (Country_Name__c = 'Canada' AND State_Province__c IN :canadaStateFilters)) AND (X2010_Census_Population__c > 0) ORDER BY City__c LIMIT 50000];
        }

        pcIds = new Map<Id, Postal_Code__c>(fullPostalCodes).keySet();
        Set<String> available = new Set<String>();
        Set<String> availableCounts = new Set<String>();
        for(Postal_Code__c pc : fullPostalCodes){
            if(String.isNotBlank(pc.City__c) && String.isNotBlank(pc.State_Province__c)){
                String state = pc.Country_Name__c == 'Canada' ? canadaStateMap.get(pc.State_Province__c) : pc.State_Province__c;
                available.add(pc.City__c + ' ' + state);

                if(String.isNotBlank(pc.County__c))
                    availableCounts.add(pc.County__c + ' County ' + state);
            }
        }

        String[] av = new String[]{};
        av.addAll(available);

        String[] avCounties = new String[]{};
        avCounties.addAll(availableCounts);
        availableCities = String.join(av,',');
        availableCounties = String.join(avCounties, ',');

        totalPop = 0;
        websiteVisits = 0;
        accountTotal = 0;

        if(autoLoad && av.size() < 10000){
            prepAggregateData(availableCities);
        }else{
            autoLoad = false;
        }
        
        System.debug(disableAddAll);
    }

    public void prepAggregateData(){
        try{

            totalPop = 0;
            websiteVisits = 0;
            accountTotal = 0;
            avgCycles = -1;

            String[] cityFilterPre = selectedCities.split(',');
            String[] cityFilter = new String[]{};
            String[] stateFilter = new String[]{};

            String[] countyFilters = new String[]{};
            String[] countyStateFilters = new String[]{};
            Set<String> countyCityFilters = new Set<String>();

            for(String city : cityFilterPre){
                if(city.toLowerCase().contains('county')){
                    Integer i = city.toLowerCase().indexOf('county');
                    String c = city.substring(0, i);
                    String state = city.substring(i + 6, city.length());

                    countyFilters.add(c.trim());
                    countyStateFilters.add(state.trim());
                    if(canadaStateMapReversed.containsKey(state.trim()))
                        countyStateFilters.add(canadaStateMapReversed.get(state.trim()));
                }else{
                    Integer i = city.lastIndexOf(' ');
    
                    String c = city.substring(0, i);
                    String state = city.substring(i, city.length());
    
                    cityFilter.add(c.trim());
                    stateFilter.add(state.trim());
                    if(canadaStateMapReversed.containsKey(state.trim()))
                        stateFilter.add(canadaStateMapReversed.get(state.trim()));
                }
            }

            if(!countyFilters.isEmpty()){
                Postal_Code__c[] pcs = [SELECT Id, City__c, State_Province__c FROM Postal_Code__c WHERE County__c IN :countyFilters AND State_Province__c IN :countyStateFilters];
                String[] selCitiesFromCounty = new String[]{};
                for(Postal_Code__c pc : pcs){
                    countyCityFilters.add(pc.City__c.trim());
                    selCitiesFromCounty.add(pc.City__c.trim() + ' ' + pc.State_Province__c);
                }

                cityFilter.addAll(countyCityFilters);
                stateFilter.addAll(countyStateFilters);
                String[] selCities = String.isBlank(selectedCities) ? new String[]{} : selectedCities.split(',');

                // selCities.addAll(selCitiesFromCounty);

                selectedCities = String.join(selCities, ',');
                selectedCitiesFromCounty = String.join(selCitiesFromCounty, ',');
            }

            System.debug(cityFilter);
            System.debug(countyStateFilters);

            Integer sizeBlock = cityFilter.size()/200 + (math.mod(cityFilter.size(),200)!=0?1:0);
            Set<String> theseIds = new Set<String>();
            
            String pcString = ApexPages.currentPage().getParameters().get('pcIds');
            String[] pcs = new String[]{};

            if(pcIds == null){

                if(pcString.length() > 500000){
                    for(Integer i = pcString.length() / 2; i < pcString.length(); i++){
                        if(pcString.charAt(i) == ','.charAt(0)){
                            String firstHalf = pcString.substring(0, i);
                            String secondHalf = pcString.substring(i + 1, pcString.length() - 1);

                            pcs.addAll(firstHalf.split(','));
                            pcs.addAll(secondHalf.split(','));

                            break;
                        }
                    }
                }else{
                    pcs.addAll(pcString.split(','));
                }

                theseIds.addAll(pcs);
            }

            for(Integer i = 0; i < sizeBlock; i++){
                Decimal tempCycles = 0;
                AggregateResult[] res = [SELECT City__c city, MAX(X2020_CS_Website_Visitors__c) siteVisits, SUM(X2010_Census_Population__c) pop, AVG(Avg_Monthly_Cycles_per_Territory__c) cycles FROM Postal_Code__c WHERE (City__c IN :cityFilter) AND State_Province__c IN :stateFilter GROUP BY City__c, State_Province__c LIMIT 200];
                
                if(res.isEmpty())
                    continue;

                for(AggregateResult r : res){
                    Integer cityInt = cityFilter.indexOf((String)r.get('city'));
                    if(cityInt != -1)
                        cityFilter.remove(cityInt);

                    totalPop += ((Decimal)r.get('pop') == null ? 0 : (Decimal)r.get('pop') * 0.65);
                    websiteVisits += ((Decimal)r.get('siteVisits') == null ? 0 : (Decimal)r.get('siteVisits'));
                    tempCycles += ((Decimal)r.get('cycles') == null ? 0 : (Decimal)r.get('cycles'));
                }

                avgCycles += tempCycles / res.size();

            }

            System.debug(avgCycles);
            System.debug(sizeBlock);
            avgCycles = Math.round(avgCycles / sizeBlock);

            if(avgCycles == -1)
                avgCycles = 0;

            cityFilterPre = selectedCities.split(',');
            cityFilter = new String[]{};
            stateFilter = new String[]{};

            if(!countyCityFilters.isEmpty())
                cityFilter.addAll(countyCityFilters);

            for(String city : cityFilterPre){
                if(city.toLowerCase().contains('county')){
                    Integer i = city.toLowerCase().indexOf('county');
                    String c = city.substring(0, i);
                    String state = city.substring(i + 5, city.length());

                    cityFilter.add(c.trim());
                    stateFilter.add(state.trim());
                    if(canadaStateMapReversed.containsKey(state.trim()))
                        stateFilter.add(canadaStateMapReversed.get(state.trim()));
                }else{
                    Integer i = city.lastIndexOf(' ');
    
                    String c = city.substring(0, i);
                    String state = city.substring(i, city.length());
    
                    cityFilter.add(c.trim());
                    stateFilter.add(state.trim());
                    if(canadaStateMapReversed.containsKey(state.trim()))
                        stateFilter.add(canadaStateMapReversed.get(state.trim()));
                }
            }

            System.debug('\'' + String.join(cityFilter, '\',\'') + '\'');

            Boolean pageNameCooltone = ApexPages.currentPage().getURL().toLowerCase().contains('cooltone');
            String activeField = pageNameCooltone ? 'CoolTone_Active__c' : 'CoolSculpting_Active__c';
            String locQuery = 'SELECT COUNT(Account__c) accCount FROM Locator_Listing__c WHERE (City__c IN :cityFilter) AND ((Country__c = \'United States of America\' AND State_ProvidenceRegion__c IN :stateFilters) OR Country__c = \'Canada\') AND Active__c = true AND ' + activeField + ' = true';
            System.debug(locQuery);
            AggregateResult fullListings = Database.query(locQuery);
            accountTotal = (Integer)fullListings.get('accCount');

        }catch(Exception e){
            System.debug(e.getMessage() + ' Line: ' + e.getLineNumber());
        }
        
    }

    public void prepAggregateData(String sel){
        try{

            totalPop = 0;
            websiteVisits = 0;
            accountTotal = 0;
            avgCycles = -1;

            String[] cityFilter = new String[]{};

            for(String s : sel.split(','))
                cityFilter.add(s.substring(0, s.lastIndexOf(' ')));

            Integer sizeBlock = cityFilter.size()/200 + (math.mod(cityFilter.size(),200)!=0?1:0);

            for(Integer i = 0; i < sizeBlock; i++){
                Decimal tempCycles = 0;
                AggregateResult[] res = [SELECT City__c city, MAX(X2020_CS_Website_Visitors__c) siteVisits, SUM(X2010_Census_Population__c) pop, AVG(Avg_Monthly_Cycles_per_Territory__c) cycles FROM Postal_Code__c WHERE Id IN :pcIds AND City__c IN :cityFilter GROUP BY City__c LIMIT 200];
                for(AggregateResult r : res){

                    Integer cityInt = cityFilter.indexOf((String)r.get('city'));
                    if(cityInt != -1)
                        cityFilter.remove(cityInt);

                    totalPop += ((Decimal)r.get('pop') == null ? 0 : (Decimal)r.get('pop'));
                    websiteVisits += ((Decimal)r.get('siteVisits') == null ? 0 : (Decimal)r.get('siteVisits'));
                    tempCycles += ((Decimal)r.get('cycles') == null ? 0 : (Decimal)r.get('cycles'));
                }

                avgCycles += tempCycles / res.size();
            }

            avgCycles = Math.round(avgCycles / sizeBlock);
            totalPop = totalPop * 0.65;

            if(avgCycles == -1)
                avgCycles = 0;

            cityFilter = new String[]{};

            for(String s : sel.split(','))
                cityFilter.add(s.substring(0, s.lastIndexOf(' ')));

            Boolean pageNameCooltone = ApexPages.currentPage().getURL().toLowerCase().contains('cooltone');
            String activeField = pageNameCooltone ? 'CoolTone_Active__c' : 'CoolSculpting_Active__c';
            String locQuery = 'SELECT COUNT(Account__c) accCount FROM Locator_Listing__c WHERE (City__c IN :cityFilter OR County__c IN :cityFilter) AND ((Country__c = \'United States of America\' AND State_ProvidenceRegion__c IN :stateFilters) OR Country__c = \'Canada\') AND Active__c = true AND ' + activeField + ' = true';
            System.debug(ApexPages.currentPage().getURL().toLowerCase());
            System.debug(activeField);
            System.debug(locQuery);
            AggregateResult fullListings = Database.query(locQuery);
            accountTotal = (Integer)fullListings.get('accCount');

        }catch(Exception e){
            System.debug(e.getMessage() + ' Line: ' + e.getLineNumber());
        }
        
    }

    @RemoteAction
    public static List<Map<String, String>> searchPractices(String term){
        List<Map<String, String>> results = new List<Map<String, String>>();
        String preppedTerm = '%' + String.escapeSingleQuotes(term) + '%';

        Account[] accs = 
            [SELECT Id, Name, Lifetime_Utilization__c 
            FROM Account 
            WHERE Type = 'Practice - Active' 
            AND 
                (Name LIKE :preppedTerm 
                OR AGN_Location_ID__c LIKE :preppedTerm 
                OR AGN_Account__c LIKE :preppedTerm)
            LIMIT 10];

        for(Account acc : accs){
            results.add(new Map<String, String>{'label' => acc.Name, 'value' => acc.Name, 'cycles' => acc.Lifetime_Utilization__c != null ? String.valueOf(acc.Lifetime_Utilization__c) : null});
        }

        return results;
    }

}

 
SwethaSwetha (Salesforce Developers) 
HI Jagadeep,
The code provided in question does not highlight the uncovered lines. Also since the code is huge and requires an understanding of your implementation, it might not be possible to provide exact edit suggestions. However, the below articles give a good insight into how coverage can be improved

https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines 

Code Coverage Best Practices
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_code_coverage_best_pract.htm

Checking Code Coverage
https://help.salesforce.com/articleView?id=code_dev_console_tests_coverage.htm&type=5

Deployment related code coverage issues
https://help.salesforce.com/articleView?id=000335222&type=1&mode=1

https://salesforce.stackexchange.com/questions/148894/help-required-to-get-full-code-covered-in-test-class

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you