+ Start a Discussion
jagadeep kjagadeep k 

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

/*
	01/19/18	BE@IC 	Created test class (00156299)
*/
@isTest
public with sharing class lmiControllerTest {
	
	public static testMethod void testControllerASM(){
		Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
			'ASM' => true,
			'ASR' => false,
			'PDM' => false,
			'PDMA' => false,
			'ISR' => false
		};

		String roleString = 'ASM';

		createSettings();

		User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
		User u;
		List<User> employeeUsers;
		// Avoid Mixed DML Operation Error
		System.runAs(thisUser) {
			u = createUser();
			insert u;
			employeeUsers = createEmployeeUsers(10,u.Id);
			insert employeeUsers;
		}

		Account a = createAccount();
		insert a;

		Locator_Listing__c ll = createLocatorListing(a.Id);
		insert ll;

		Test.startTest();
			Postal_Code__c pc = createPostalCode(u.Id,roleString);
			insert pc;
			LMIController ctrl = resetController(u.Id);
			ctrl.cityResults();
			testLocatorListings(ctrl, ll, roleString);
			testRoles(ctrl,roleCheckMap, roleString);
            testCityListUsers(ctrl,pc, roleString);
            ctrl.selectedCities = 'TestCnty County';
            ctrl.prepAggregateData();
            delete pc;
		Test.stopTest();

		ctrl = resetController();
		ctrl.cityResults();
		System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
	}

	public static testMethod void testControllerASR(){
		Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
			'ASM' => false,
			'ASR' => true,
			'PDM' => false,
			'PDMA' => false,
			'ISR' => false
		};

		String roleString = 'ASR';

		createSettings();

		User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
		User u;
		List<User> employeeUsers;
		// Avoid Mixed DML Operation Error
		System.runAs(thisUser) {
			u = createUser();
			insert u;
			employeeUsers = createEmployeeUsers(10,u.Id);
			insert employeeUsers;
		}

		Account a = createAccount();
		insert a;

		Locator_Listing__c ll = createLocatorListing(a.Id);
		insert ll;

		Test.startTest();
			Postal_Code__c pc = createPostalCode(u.Id,roleString);
			insert pc;
			LMIController ctrl = resetController(u.Id);
			ctrl.cityResults();
			testLocatorListings(ctrl, ll, roleString);
			testRoles(ctrl,roleCheckMap, roleString);
			testCityListUsers(ctrl,pc, roleString);
			delete pc;
		Test.stopTest();

		ctrl = resetController();
		ctrl.cityResults();
		ctrl.prepAggregateData();
		System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
	}	

	public static testMethod void testControllerPDM(){
		Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
			'ASM' => false,
			'ASR' => false,
			'PDM' => true,
			'PDMA' => false,
			'ISR' => false
		};

		String roleString = 'PDM';

		createSettings();

		User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
		User u;
		List<User> employeeUsers;
		// Avoid Mixed DML Operation Error
		System.runAs(thisUser) {
			u = createUser();
			insert u;
			employeeUsers = createEmployeeUsers(10,u.Id);
			insert employeeUsers;
		}

		Account a = createAccount();
		insert a;

		Locator_Listing__c ll = createLocatorListing(a.Id);
		insert ll;
		
		Test.startTest();
			Postal_Code__c pc = createPostalCode(u.Id,roleString);
			insert pc;
			LMIController ctrl = resetController(u.Id);
			ctrl.cityResults();
			testLocatorListings(ctrl, ll, roleString);
			testRoles(ctrl,roleCheckMap, roleString);
			testCityListUsers(ctrl,pc, roleString);
			delete pc;
		Test.stopTest();

		ctrl = resetController();
		ctrl.cityResults();
		System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
	}	

	public static testMethod void testControllerPDMA(){
		Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
			'ASM' => false,
			'ASR' => false,
			'PDM' => false,
			'PDMA' => true,
			'ISR' => false
		};

		String roleString = 'PDMA';

		createSettings();

		User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
		User u;
		List<User> employeeUsers;
		// Avoid Mixed DML Operation Error
		System.runAs(thisUser) {
			u = createUser();
			insert u;
			employeeUsers = createEmployeeUsers(10,u.Id);
			insert employeeUsers;
		}

		Account a = createAccount();
		insert a;

		Locator_Listing__c ll = createLocatorListing(a.Id);
		insert ll;

		Test.startTest();
			Postal_Code__c pc = createPostalCode(u.Id,roleString);
			insert pc;
        PageReference pageRef = Page.lmiTool2;
        Test.setCurrentPage(pageRef);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(pc);
        ApexPages.currentPage().getParameters().put('Id',u.id);
      	//	LMIController ctrl1 = new LMIController(sc);
			LMIController ctrl = resetController(u.Id);
       // String term;
        ctrl.prepAggregateData();
      //  ctrl.searchPractices(term);
			ctrl.cityResults();
			testLocatorListings(ctrl, ll, roleString);
			testRoles(ctrl,roleCheckMap, roleString);
			testCityListUsers(ctrl,pc, roleString);
			delete pc;
		Test.stopTest();

		ctrl = resetController();
		ctrl.cityResults();
		System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
	}	

	public static testMethod void testControllerISR(){
		Map<String,Boolean> roleCheckMap = new Map<String,Boolean> {
			'ASM' => false,
			'ASR' => false,
			'PDM' => false,
			'PDMA' => false,
			'ISR' => true
		};

		String roleString = 'ISR';

		createSettings();

		User thisUser = [SELECT Id From User WHERE Id = :UserInfo.getUserId()];
		User u;
		List<User> employeeUsers;
		// Avoid Mixed DML Operation Error
		System.runAs(thisUser) {
			u = createUser();
			insert u;
			employeeUsers = createEmployeeUsers(10,u.Id);
			insert employeeUsers;
		}

		Account a = createAccount();
		insert a;

		Locator_Listing__c ll = createLocatorListing(a.Id);
		insert ll;
        
		Test.startTest();
			Postal_Code__c pc = createPostalCode(u.Id,roleString);
			insert pc;
        PageReference pageRef = Page.lmiTool2;
        Test.setCurrentPage(pageRef);
        ApexPages.Standardcontroller sc = new ApexPages.Standardcontroller(pc);
        ApexPages.currentPage().getParameters().put('Id',u.id);
        
     //   lmiController lc = new lmiController(sc);
			LMIController ctrl = resetController(u.Id);
        	ctrl.prepAggregateData();
			ctrl.cityResults();
			testLocatorListings(ctrl, ll, roleString);
			testRoles(ctrl,roleCheckMap, roleString);
			testCityListUsers(ctrl,pc, roleString);
			delete pc;
		Test.stopTest();

		ctrl = resetController();
		ctrl.cityResults();
		System.assertEquals(UserInfo.getUserId(),ctrl.toolUserId);
	}	


	// For the case of this test class, we are only using Colorado (CO), a Western state in the US.
	private static void testLocatorListings(LMIController ctrl, Locator_Listing__c ll, String currentRoleString) {
		String roleString = 'Testing role: ' + currentRoleString;
        
    String   locQuery ='SELECT COUNT(Account__c) accCount FROM Locator_Listing__c WHERE (City__c=\'Test\') AND ((Country__c = \'United States of America\' AND State_ProvidenceRegion__c=\'CO\') OR Country__c = \'Canada\') AND Active__c = true AND CoolTone_Active__c = true';
		ctrl.prepAggregateData();
        //	System.assertEquals(1,ctrl.accountTotal, roleString);
	}

	private static void testRoles(LMIController ctrl, Map<String,Boolean> roleCheckMap, String currentRoleString) {
		String roleString = 'Testing role: ' + currentRoleString;
		
		System.assertEquals(roleCheckMap.get('ASM'),ctrl.isASM, roleString);
		System.assertEquals(roleCheckMap.get('ASR'),ctrl.isASR, roleString);
		System.assertEquals(roleCheckMap.get('PDM'),ctrl.isPDM, roleString);
		System.assertEquals(roleCheckMap.get('PDMA'),ctrl.isAssocPDM, roleString);
		System.assertEquals(roleCheckMap.get('ISR'),ctrl.isISR,roleString);
		System.assertEquals(true, ctrl.isManager, roleString);
	}

	// For the case of this test class, we are only using Colorado (CO), a Western state in the US.
	private static void testCityListUsers(LmiController ctrl, Postal_Code__c pc, String currentRoleString) {
        ctrl.prepAggregateData();
		String roleString = 'Testing role: ' + currentRoleString;
		System.assertEquals(1,ctrl.fullPostalCodes.size(), roleString);
        
      //  System.assertEquals(500001,ctrl.fullPostalCodes.size(), roleString);
	}

	private static lmiController resetController() {
		PageReference p = new PageReference('Page.lmiTool2');
		p.getParameters().put('autoLoad', 'true');
		Test.setCurrentPageReference(p);
        System.currentPageReference().getParameters().remove('id');
		return new LMIController();
	}

	private static LMIController resetController(Id userId) {
		PageReference p = new PageReference('Page.lmiTool2');
		p.getParameters().put('autoLoad', 'true');
		Test.setCurrentPageReference(p);
		System.currentPageReference().getParameters().put('id', userId);
		return new LMIController();
	}

	private static User createUser() {
		return new User(
			ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
			FirstName = 'Zeltiq',
			LastName = 'TestUser',
			Email = 'ZeltiqTest@Test.com',
			Username = 'ZeltiqTest@Test.com' + System.currentTimeMillis(),
			CompanyName = 'ZeltiqTest',
			Title = 'title',
			Alias = 'alias',
			TimeZoneSidKey = 'America/Los_Angeles',
			EmailEncodingKey = 'UTF-8',
			LanguageLocaleKey = 'en_US',
			LocaleSidKey = 'en_US'
		);
	}

	private static List<User> createEmployeeUsers(Integer amount, Id managerUserId) {
		Id sysAdminId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id;
		List<User> employees = new List<User>();
		for(Integer i = 0; i < amount; i++) {
			employees.add(new User(
				ProfileId = sysAdminId,
				FirstName = 'Zeltiq',
				LastName = 'Employee ' + i,
				Email = 'ZeltiqTest' + i + '@Test.com',
				Username = 'ZeltiqTest' + i + '@Test.com' + System.currentTimeMillis(),
				CompanyName = 'ZeltiqTest',
				Title = 'title',
				Alias = 'alias',
				TimeZoneSidKey = 'America/Los_Angeles',
				EmailEncodingKey = 'UTF-8',
				LanguageLocaleKey = 'en_US',
				LocaleSidKey = 'en_US',
				ManagerId = managerUserId
			));
		}
		return employees;
	}

	private static Postal_Code__c createPostalCode(Id userId, String userField) {
     //  List<Postal_Code__c> 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='Test' AND State_Province__c='CO' GROUP BY City__c, State_Province__c LIMIT 200];
                        
		Postal_Code__c pc = new Postal_Code__c(
			Country_Name__c = 'United States America',
			Name = '12345',
			State_Province__c = 'CO',
			X2020_CS_Website_Visitors__c = 10,
			X2010_Census_Population__c = 10,
          //  Avg_Monthly_Cycles_per_Territory__c =10,
            City__c = 'Test',
            County__c = 'TestCnty'
		);
		if(userField == 'ASM') {
			pc.Area_Sales_Manager__c = userId;
		}
		else if(userField == 'ASR') {
			pc.Area_Sales_Rep__c = userId;
		}
		else if(userField == 'PDM') {
			pc.Practice_Development_Manager__c = userId;
		}
		else if(userField == 'PDMA') {
			pc.Level_1_Practice_Development_Manager__c = userId;
		}
		else if(userField == 'ISR') {
			pc.Inside_Sales_Rep__c = userId;
		}
		return pc;
        
	}

	private static Account createAccount() {
		return new Account(
			Name = 'Test Account',
            External_ID__c = '12345',
			Type = 'Practice - Active',
            Lifetime_Utilization__c=10,
            AGN_Location_ID__c='TestLoc'
		);
	}

	private static Locator_Listing__c createLocatorListing(Id accountId) {
		Locator_Listing__c[] listings = new Locator_Listing__c[]{};

		return new Locator_Listing__c(
			Name = 'Test Locator Listing',
			Account__c = accountId,
			State_ProvidenceRegion__c = 'CO',
			Country__c = 'United States of America',
            City__c = 'Test',
			Active__c = true
		);
	}

	private static void createSettings() {
        Apex_Code_Settings__c testCustomSettings = new Apex_Code_Settings__c();
        testCustomSettings.GooglePrivateKey__c = 'a3--l2CjL5iGR6tOOnQrMOM5Ics=';
        testCustomSettings.GoogleClientID__c = 'gme-allerganinc';
        insert testCustomSettings;
	}
}