function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kenji775Kenji775 

Dumb OOP question

Hey all,

I'm still getting the hang of object oriented programming, and I'm not sure how to solve this problem without "global variables".

 

Basically I have a large testing class. There is a seperate sub class for each trigger, page, and class that need to be tested. A lot of these tests though need the same type of data (contacts, accounts, leads, etc). How can I create one contact, one account, one lead, and let all the sub classes read from it and write to it? These being test classes, I cannot control what data is passed to them. So for example I have something like.

 

 

public static contact createTestContact()
{
    Contact testContact = new Contact(Firstname='Frank', Lastname='Jones');

       insert testContact;
       return testContact;
}

public testMethod void testContactTrigger1()
{
       Contact myContact = createTestContact();
       //Do some stuff
}

public testMethod void testContactOtherTrigger()
{
       Contact myContact = createTestContact();
       //Do some different stuff
}

 

How can I let testContactTrigger and testContactOtherTrigger share the same contact? I don't need two copies of the same contact, or the additional overhead that comes from instantiating it twice. Just once would be fine. Can I modify the createTestContact method to know when it has already created a contact once, and just return the same contact next time it is called?

 

Anand@SAASAnand@SAAS

I would create a "TestDataHelper" class that has static methods (very similar to the one you have below) and use "private" variables that will return same instance of contact when not "null" in your "createTestcontact" method.

 

However if your trigger/page/controllers require a new contact record, i would probably create a new contact record for every test method that requires it.

 

While there's a minor overhead during test execution process,it does'nt impact the performance of the final apex/trigger code when they execute in your production environment.

Kenji775Kenji775

Thanks for the reply. Would you be willing to provid a small code sample of what you are thinknig about? I kinda think I get what you are saying, but not totally. Thanks for the help.

dnakonidnakoni

Here's an example

 

 

public class TestHelper {
     private static Contact c;
     private static Account a;

     public static Contact getContact() {
          if (c == null) {
               c = new Contact (FirstName='test', LastName='test');
          }

          return c;
     }

     public static Account getAccount() {
          if (a == null) {
               a = new Account (Name='test');
          }
 
          return a;
     }
}

 

 

Then in your test method you can do something like this:

 

 

Contact c = TestHelper.getContact();

 Of course you can also INSERT them in the TestHelper class if you need to.

 

 Hope that helps!

 

Kenji775Kenji775

Ah, perfect thank you. With my real code I was close. I just didn't declair the actual variables outside of the class. Got it, thanks!

Kenji775Kenji775

Okay, I'm exhausted. I've been workong on this testing class for 3 days now (on and off) and I am just not making much progress. I though declaring my variables as public static in the super class would make them accessible to all the child classes, but that is not the case. I feel like this thing has gotten overly complex and horribly inflexible. Right now the errors I am getting are all basically "error attempting to de-reference a null object" when one of my helper classes tries to use a variable that was set in another helper class. I feel very lost and I don't know what I'm doing. Any input would be much appreciated. Thanks.

@isTest
private class unitTests 
{
	
	private static DateTime dT = System.now();
    private static Date timeout = date.newinstance(dT.year(), dT.month(), dT.day());
	private static Contact testContact;
	private static Contact testContact2;
    private static Account testAccount;
	private static Campaign testUmbrellaCampaign;
	private static Campaign testParentCampaign;
	private static Campaign testChildCampaign;
	private static Respondent__c testRespondent;
	private static Respondent__c testRespondent2;
	private static Respondent__c testRespondent3;
	private static Case testCase; 
	private static Case testCase2; 		
	
	public static Account createTestAccount()
	{
		if(testAccount == null)
		{
        	//make an account so we can attach a contact to it
        	Account localTestAccount = new Account(name='My Test Account', Tax_ID__c='99-9999999');
        	return localTestAccount;
		}
		else
		{
			return testAccount;
		}	
	}
	
	public static Contact createTestContact()
	{
		if(testContact == null)
		{

	        date birthdate = date.parse('03/21/1988');
	        Contact localTestContact = new Contact(Firstname='Frank', 
	        									Lastname='Jones', 
	        									AccountID=testAccount.id, 
	        									of_PSA__c=0, 
	        									of_No_shows__c =0, 
	        									of_Cancellations__c =0, 
	        									of_Disqualified__c =0, 
	        									of_Participations__c =0, 
	        									MailingCity='coon rapids', 
	        									MailingCountry = 'us', 
	        									MailingState='MN', 
	        									MailingStreet='432423 nowhere street', 
	        									MailingPostalCode='45543',
	        									phone = '7625324246',
	        									birthdate = birthdate);
	        return localTestContact;
		}
		else
		{
			return testContact;
		}
	}
 
 	public static Campaign createtestUmbrellaCampaign()
 	{	

		if(testUmbrellaCampaign == null)
		{
	 		RecordType UmbrellaRecordType = [select id from RecordType where name = 'FPI Umbrella Campaign'];
	        //Create the Umbrella Campaign
	        Campaign localtestUmbrellaCampaign = new Campaign(name='My Test Account Campaign Master', 
	                        Incentive_Amount_Paid_for_Study__c=20.00, 
	                        Time_Slot__c='MASTER', Status='Active', 
	                        Recruits_Per_Time_Slot__c=1, 
	                        IVR_Description__c = 'Test',
	                        Respondent_timeout__c = timeout,
	                        Project_Manager__c = testContact.id,                           
	                        RecordTypeID=UmbrellaRecordType.id); 
	        return localtestUmbrellaCampaign; 
		}
		else
		{
			return testUmbrellaCampaign;
		}               	
 	}
     
    public static Campaign createTestParentCampaign()
    { 		
    	if(testParentCampaign == null)
    	{
    		
	    	RecordType ParentRecordType = [select id from RecordType where name = 'FPI Parent Campaign'];
	        //Create the Parent Campaign
	        Campaign localTestParentCampaign = new Campaign(name='My Test Account Campaign Master', 
	                        Incentive_Amount_Paid_for_Study__c=20.00, 
	                        Time_Slot__c='MASTER', Status='Active', 
	                        Recruits_Per_Time_Slot__c=1, 
	                        IVR_Description__c = 'Test',
	                        Parentid=testUmbrellaCampaign.id,
	                        Respondent_timeout__c = timeout,
	                        isActive = true,                           
	                        Criteria_1_Quota__c = 3, 
	                        Criteria_2_Quota__c = 3, 
	                        Criteria_3_Quota__c = 3, 
	                        Criteria_4_Quota__c = 3, 
	                        Criteria_5_Quota__c = 3, 
	                        Criteria_6_Quota__c = 3, 
	                        Criteria_7_Quota__c = 3, 
	                        Criteria_8_Quota__c = 3, 
	                        Criteria_9_Quota__c = 3,
	                        Criteria_10_Quota__c = 3,
	                        Update_Respondent_Status__c = true,
	                        Update_Status_To__c = 'active',
	                        Project_Manager__c = testContact.id,
	                        callers__c = 'Daniel Llewellyn;Carlos Villalpando',
	                        RecordTypeID=ParentRecordType.id);
	        
        	return localTestParentCampaign;
    	}
    	else
    	{
    		return testParentCampaign;
    	}
    }    
	
	public static Campaign createTestChildCampaign()
	{   
		if(testChildCampaign == null)
		{
		    RecordType ChildRecordType = [select id from RecordType where name = 'FPI Child Campaign'];		
			      
	        //Create the Child Campaign
	        Campaign localTestChildCampaign = new Campaign(Parentid=testParentCampaign.id,
	    									  name='My Test Account Campaign', 
	    									  Time_Slot__c='1pm', 
	    									  Incentive_Amount_Paid_for_Study__c=20.00, 
	    									  Status='Planned', Recruits_Per_Time_Slot__c=1, 
	    									  IVR_Description__c = 'Test', 
	    									  RecordTypeID=ChildRecordType.id,
	    									  Project_Manager__c = testContact.id);
	    
	        return localTestChildCampaign;
		}
		else
		{
			return testChildCampaign;
		}
	}

	public static Respondent__c createTestRespondent()
	{
		//Insert the first contact using a PID instead of inserting a contact ID. The trigger shoudl use the PID to look up the contact ID and fill it in.
        if(testRespondent == null)
        {
        	Respondent__c localTestRespondent = new Respondent__c(Master_Campaign__c=testParentCampaign.id, 
											Child_Campaign__c=testChildCampaign.id, 
											Respondent_PID__c = testContact.pid__c, 
											     
    										Criteria_1_Met__c = 'yes', 
    										Criteria_2_Met__c = 'yes', 
    										Criteria_3_Met__c = 'yes', 
    										Criteria_4_Met__c = 'yes', 
    										Criteria_5_Met__c = 'yes', 
    										Criteria_6_Met__c = 'yes', 
    										Criteria_7_Met__c = 'yes', 
    										Criteria_8_Met__c = 'yes', 
    										Criteria_9_Met__c = 'yes', 
    										Criteria_10_Met__c = 'yes');    
        	return localTestRespondent;
        }
        else
        {
        	return testRespondent;
        }
	}
	public static Link_Category__c createTestLinkCategory()
	{
        //Create a link category
        Link_Category__c linkCategory = new Link_Category__c(Name = 'About', 
					                                                Link_Class__c = 'about',
					                                                Label__c = 'about', 
					                                                HTML_ID__c = 'about',
					                                                CSS_Class__c = 'about');
        return linkCategory;
	}
    
    public static Link_Item__c createTestLinkItem(Id linkCategory)
    {    
    	if(linkCategory == null)
    	{
    		linkCategory = createTestLinkCategory().id;
    	}
        //Create link item
        Link_Item__c linkItem = new Link_Item__c(Name = 'home',
        										   Link_URL__c = 'http://www.google.com',
        										   Link_Category__c = linkCategory);
        return linkItem;										   									                                               
	}

	public static Case createTestCase()
	{	
		testCase = new case(contact = testContact, status = 'Open', Origin = 'Web', subject='This is a test case. Eat face');		
		return testCase;
	}

	static testMethod void testPreventDupeCases()
	{
        
        try
        {
	        //***************** TEST PreventDupeCases trigger ********************************
			//Try to create the same case twice. Second one should error.
	
			testCase = createTestCase();
			
			testCase2 = createTestCase();
        }
		
		catch(Exception e)
		{
			system.debug('Adding 2nd case failed. This is good');
		}
	}
	static testMethod void testPopulateRespondentInfo()
	{
		//***************** TEST PopulateRespondentInfo Trigger ********************************
		//Those resondents we made above should have caused the FlagRespondentsAsRecentlyTested
		//trigger to fire. That means those contacts should have the  recently_tested__c flag to true
		
		Contact thisTestContact = createTestContact();
		Campaign thisTestParentCampaign = createTestParentCampaign();
		Campaign thisTestChildCampaign = createTestChildCampaign();
        Contact contact1details = [select recently_tested__c, pid__c, id from Contact  where id = :thisTestContact.id];

        //Insert the second contact using just a regular contact ID, so the other half of the trigger will fire, that should fill in the PID.
        Respondent__c Respondent2 = new Respondent__c(Master_Campaign__c=thisTestParentCampaign.id, 
        											  Child_Campaign__c=thisTestChildCampaign.id, 
        											  Respondent__c=thisTestContact.Id, 
        											  Respondent_PID__C = 
        											  testContact.PID__c,
                									  Criteria_1_Met__c = 'no', 
                									  Criteria_2_Met__c = 'no', 
                									  Criteria_3_Met__c = 'no', 
                									  Criteria_4_Met__c = 'no', 
                									  Criteria_5_Met__c = 'no', 
                									  Criteria_6_Met__c = 'no', 
                									  Criteria_7_Met__c = 'no', 
                									  Criteria_8_Met__c = 'no', 
                									  Criteria_9_Met__c = 'no', 
                									  Criteria_10_Met__c = 'no');    
        insert Respondent2;

        //Insert the second contact using just a regular contact ID, so the other half of the trigger will fire, that should fill in the PID.
        try
        {
	        Respondent__c Respondent3 = new Respondent__c(Master_Campaign__c=testParentCampaign.id, 
	        											  Child_Campaign__c=testChildCampaign.id, 
	        											  Respondent_PID__C = '123412',
	                									  Criteria_1_Met__c = 'no', 
	                									  Criteria_2_Met__c = 'no', 
	                									  Criteria_3_Met__c = 'no', 
	                									  Criteria_4_Met__c = 'no', 
	                									  Criteria_5_Met__c = 'no', 
	                									  Criteria_6_Met__c = 'no', 
	                									  Criteria_7_Met__c = 'no', 
	                									  Criteria_8_Met__c = 'no', 
	                									  Criteria_9_Met__c = 'no', 
	                									  Criteria_10_Met__c = 'no');    
	        insert Respondent3;   
        }
        catch(Exception e)
        {
        	System.debug('Inserting 3rd Respondent Failed. Caught be bad PID');	
        }    
	}
	
	static testMethod void testPaymentDuplicatePreventor()
	{

		Contact thisTestContact = createTestContact();
		Campaign thisTestChildCampaign = createTestChildCampaign();		
		
        //***************** TEST Payment Duplicate Preventor ********************************
        Payments__c payment1 = new Payments__c(Contact__c = testContact.id, Respondent_Number__c = 5, status__c = 'tested', Study__c = thisTestChildCampaign.id);
        Payments__c payment2 = new Payments__c(Contact__c = testContact.id, Respondent_Number__c = 5, status__c = 'tested', Study__c = thisTestChildCampaign.id);
        insert payment1;
		try
		{
			insert payment2;
		}
		catch(Exception e)
		{
			system.debug('Adding 2nd payment failed. This is good');
		}   
	}
	
	static testMethod void testUpdateUmbrellaCounters()
	{  
        //***************** TEST Update Umbrella Counters ********************************
        //This just recalculates counters, so just run an udate statment on it.
        UpdateTopLevelCampaignCounters updateCounterController = new UpdateTopLevelCampaignCounters();
		boolean updateCampaignSuccess;
		updateCampaignSuccess = updateCounterController.updateCountersSchedule();
		
		boolean updateCampaignSuccess2 = UpdateTopLevelCampaignCounters.updateCountersTrigger();
  
	}
	
	static testMethod void testFlagRespondentsAsRecentlyTested()
	{
	
		     
		//***************** TEST FlagRespondentsAsRecentlyTested ********************************
		//Those resondents we made above should have caused the FlagRespondentsAsRecentlyTested
		//trigger to fire. That means those contacts should have the  recently_tested__c flag to true
		Contact thisTestContact = createTestContact();

		Contact contact1details = [select recently_tested__c, pid__c, id from Contact  where id = :thisTestContact.id];
		
		System.assertEquals(contact1details.recently_tested__C,true);
	}
	
	static testMethod void testInactivateCampaignOnRecruitFill()
	{

		//***************** TEST InactivateCampaignOnRecruitFill Trigger ********************************
		//Those resondents we made above should have caused the InactivateCampaignOnRecruitFIll
		//trigger to fire. That means the master campaign status should be 'Initial Recruitment Complete'	
		
		Respondent__c thisTestRespondent = createTestRespondent();
		//Update a respondent to test the cancel logic
		thisTestRespondent.Respondent_Status__c = 'cancelled';
		update thisTestRespondent;
		
		//Then delete them to test the counter logic
		delete thisTestRespondent;
		//System.assertEquals(campaign.Status,'Initial Recruitment Complete');
	}
	
	static testMethod void testAssignCallers()
	{							

		Campaign thisTestParentCampaign = createTestParentCampaign();
		//Modify a campaign to use the assign callers trigger
		
		//for whatever reason we need a lead for a campaign member, so we better make one
		Lead lead1 = new Lead(company = 'Big stupid butt store',  firstname='Daniel', lastname='llewellyn', status='open');
		insert lead1;
		
		//Create the proper campaign member status
		CampaignMemberStatus newstatus = new CampaignMemberStatus(HasResponded = true, isDefault = true, SortOrder = 20, CampaignId = thisTestParentCampaign.id, label = 'Qualified-Callers');
		insert newstatus;
		
		//Create a campaign member so there is someone to assign a caller to
		CampaignMember member1 = new CampaignMember(leadid = lead1.id, status = 'Qualified-Callers', Contactid= testContact.id, Token__c = 'asfasdfasfas', Campaignid = thisTestParentCampaign.id);
		insert member1;
		
		//update the parent campaign record so that the trigger fires
		
		testParentCampaign.Assign_Callers__c = true;
		update thisTestParentCampaign;	
	}
	
	static testMethod void testMakRespondentCheckGen()
	{
		
		
		//***************** TEST MakRespondentCheckGen trigger and MarkRespondentcheckGenClass **********
		
		//Insert the check record, with testContact as the contact
		Contact thisTestContact = createTestContact();
		Campaign thisTestParentCampaign = createTestParentCampaign();
		Campaign thisTestChildCampaign = createTestChildCampaign();
		Respondent__c thisTestRespondent = createTestRespondent();
		
		Check__c Check1 = new Check__c(contact__c = thisTestContact.id, 
									   Master_campaign__c = thisTestParentCampaign.id, 
									   Payment_Amount__c =15.00,
									   Respondent__c=thisTestRespondent.id,
									   Session__c=thisTestChildCampaign.id,
									   Unique_Check_Record_ID__c='AAGDSFABADFAHADFADFAGASDFAFSDAF');
		insert Check1;
		Respondent__c respondentCheckTest = [select Check_Has_Been_Generated__c 
											 from Respondent__c  where id = :thisTestRespondent.id];
		
		//System.assertEquals(respondentCheckTest.Check_Has_Been_Generated__c,true);
	}
	
	static testMethod void testQueryToJson()
	{
		String myRunResult;
		//***************** TEST queryToJSON class ********************************
		//send a query to the query to json component, get some data back
		
		
	    try
	    {
			PageReference pageRef1 = Page.queryToJson;
			pageRef1.getParameters().put('queryString','name from contact');
			Test.setCurrentPageReference(pageRef1);
			QueryToJSON jsonCtlr = new queryToJSON();
			jsonCtlr.getJson();
			myRunResult = jsonCtlr.getResult();
			//System.assert(jsonCtlr.getJson()=='expected value');
		    System.Debug('Query To JSON Returned'+myRunResult );
	    }
	    catch(Exception e)
	    {
	    	
	    }
	}
		
	static testMethod void testgetJsonEvents()
	{	
		//***************** TEST getJsonEvents class ********************************
		//send a query to the query to json component, get some data back
		String myRunResult;
		
		try
		{
			PageReference opsCalendar = Page.OpsCalendar;
			opsCalendar.getParameters().put('start','1262332800');
			opsCalendar.getParameters().put('end','1263178646');
			Test.setCurrentPageReference(opsCalendar);
			getJsonEvents eventsCtlr = new getJsonEvents();
			eventsCtlr.getEvents();
			eventsCtlr.getResult();
			
			myRunResult = eventsCtlr.getResult(); 
			
			//System.assert(jsonCtlr.getJson()=='expected value');
		    System.Debug('get JSON Events result'+myRunResult );		
	    }
	    catch(Exception e)
	    {
	    	
	    }
	}
	
		
	static testMethod void testquotaCheck()	
	{
		//***************** TEST quotaCheck page and quotaTest class ********************************
		//send a query to the query to json component, get some data back
		String myRunResult;

		Contact thisTestContact = createTestContact();
		Campaign thisTestParentCampaign = createTestParentCampaign();
		Campaign thisTestChildCampaign = createTestChildCampaign();
		Respondent__c thisTestRespondent = createTestRespondent();
				
		try
		{		
			PageReference quotacheck = Page.quotaCheck;
			quotacheck.getParameters().put('CC',thisTestChildCampaign.id);
			quotacheck.getParameters().put('MC',thisTestParentCampaign.id);
			quotacheck.getParameters().put('R',thisTestContact.id);
			Test.setCurrentPageReference(quotacheck);
			quotaTest quotaTestCtlr = new quotaTest();
			quotaTestCtlr.respondentCanSchedule();
			myRunResult = quotaTestCtlr.getResult(); 
			//System.assert(jsonCtlr.getJson()=='expected value');
			System.Debug('Quota Check Returned'+myRunResult);
	    }
	    catch(Exception e)
	    {
	    	
	    }			
	}
	
	static testMethod void testWebsiteMenu()	
	{
		//***************** TEST index and website Menu ********************************
		//call the index page, which will load the websiteMenu class
		try
		{
			PageReference indexPage= Page.index;
			Test.setCurrentPageReference(indexPage);
			WebsiteMenu  websiteMenuCtlr = new WebsiteMenu();
			websiteMenuCtlr.getMenuItems();
			System.Debug('Website Menu Returned'+websiteMenuCtlr);
	    }
	    catch(Exception e)
	    {
	    	
	    }
	}
	
}