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
KevSnellKevSnell 

Task Controller - Test Method Help

Hi All,

 

I have created a Task Controller and Visualforce Page so a User can click a button on a custom object and it will create a prepopulated Task.  Meaning the User then just needs to click "Create Task".  This all works fine, however, still being an amature I can't get the TestMethod to work. 

 

If anyone could point me in the right direction I would really appreciate it.

 

public class Custom_Referral_Task_Controller { 
 
    Id idReferralClass = null;
    public Referral__c ReferralCurrent {get;set;}
    public Task tskNew {get;set;}

    public void createTaskRecord() {

        tskNew = new Task();
   
        tskNew.OwnerId = '005E0000000YhNn';
        tskNew.WhoId = '003M0000008jjA5';
        tskNew.WhatId = 'a06M0000002pW2o';
        tskNew.Subject = 'Referral Validation';
        tskNew.ActivityDate = date.today() + 7;
        tskNew.ReminderDateTime = datetime.now() + 7;
        tskNew.Description = 'Test Task'; // Pull concatenated text see above
    }

    public PageReference saveAndProceed() {

       
        //Insert Task
        try {
            insert tskNew;

        } 
        catch(DMLException e) {
            tskNew.addError(e.getMessage());
            return null;
        }

        // Return URL to Referral Object
        PageReference pf = new PageReference('/' + ReferralCurrent.Id);
        pf.setRedirect(true);
        return pf;
    }

}

 

So I tried creating the below TestMethod, however, I get 0% coverage.  I think my issue is I'm not actual testing the controller but I'm not sure where I am going wrong.

 

static testmethod void testCustomReferralTaskController() {

	try
	{
	
    Test.startTest();
    	//Create Referrer
    	VistageTestData data = new VistageTestData();
    	Account[] testAccounts = data.gimmeAccounts(2);
    	Contact testContact = data.gimmeContacts(testAccounts)[0];
    	Contact testContactDetails = [SELECT Id, FirstName, LastName, Staff__c FROM Contact WHERE Id = :testContact.Id];
    	testContactDetails.Staff__c = true;
    	update testContactDetails;
    
	//Create Referral
	VistageTestData data2 = new VistageTestData();
	Account[] testAccounts2 = data2.gimmeAccounts(2);
	Contact testContact2 = data2.gimmeContacts(testAccounts)[0];
	Contact testContactDetails2 = [SELECT Id, FirstName, LastName, Staff__c FROM Contact WHERE Id = :testContact.Id];
	testContactDetails2.Member__c = true;
	update testContactDetails2;    
    
	Referral__c Referral = new Referral__c(
        Referrer__c = testContactDetails.Id,
        Contact_Referral_Name__c = testContactDetails2.Id
		);
        insert Referral;
            
	Task testTask = new Task (
		WhoId = testContactDetails2.Id,
		WhatId = Referral.Id,
		Subject = 'Referral Validation',
		ActivityDate = date.today() + 7,
		ReminderDateTime = datetime.now() + 7,
		Description = 'Please Validate the Referral');
	insert testTask; 
    
   	Task t = [Select Id, whoid from Task where WhatId = :Referral.Id Limit 1];
   	system.assertEquals(t.whoid,testContactDetails2.Id);
   	Test.stopTest();
	
	}
	catch(exception e)
	{
		system.assertequals(e,null);
	}

} 

 

Many thanks in advance for any help or guidance.


Kev

 

Best Answer chosen by Admin (Salesforce Developers) 
sfcksfck

Hi,

 

The problem is with this line in the test method:

 

Custom_Referral_Task_Controller c=new Custom_Referral_Task_Controller();

You are trying to create a new Custom_Referral_Task_Controller without passing in any parameters. This is throwing an error 


because you have defined the constructor to require a standard controller as a parameter here:

 

public Custom_Referral_Task_Controller(ApexPages.StandardController conMain) { etc....

 So if you want to create one in your testmethod you will need to create a standard controller and pass that in. 


All Answers

Navatar_DbSupNavatar_DbSup

Hi,


Try the below code as reference of Test Class:
@isTest
private class testTriggerinsert_Contact_Activity11
{
public static testMethod void unitTestinsert_Contact_Activity4Task()
{
Custom_Referral_Task_Controller c=new Custom_Referral_Task_Controller();
c.createTaskRecord();
c.saveAndProceed();
}
}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

KevSnellKevSnell

Thanks that is a great step forward and now shows 76% coverage.

 

However, I have a test failure saying:

System.NullPointerException: Attempt to de-reference a null object

Class.Custom_Referral_Task_Controller.saveAndProceed: line 34, column 1 Class.Custom_Referral_Task_Controller.unitTestinsert_Contact_Activity4Task: line 44, column 1

 

And it also looks like the below code is not being tested meaning I'm not getting the 100%.

 

}
catch(DMLException e) {
tskNew.addError(e.getMessage());
return null;
}

 

// Return URL to Referral Object
PageReference pf = new PageReference('/' + ReferralCurrent.Id);
pf.setRedirect(true);
return pf;
}

 

sfcksfck

Hi,

 

It looks as though this is what is happening:

 

ReferralCurrent is never given a value, so when it gets to this line

 

PageReference pf = new PageReference('/' + ReferralCurrent.Id);

 

it throws the null pointer exception because ReferralCurrent is null.

 

That is probably what is stopping the test from covering that part of the code, too. So you need to set ReferralCurrent to something and that should fix those two problems.

 

The reason this code is not being covered

 catch(DMLException e) {
            tskNew.addError(e.getMessage());
            return null;
        }

 

is that it only runs when a task fails to insert. I don't think it is so important to test that bit of code. A better use of your time would be to put some assertions in your tests, which won't increase the coverage but will make the tests a lot more useful and powerful.

 

 

 

KevSnellKevSnell

Hi All,

 

I'm still stuck on getting this right, thanks to sfck I got closer, however, I updated my code and now get the below error: 

 

Error: Compile Error: Constructor not defined: [Custom_Referral_Task_Controller].<Constructor>() at line 46 column 35

 

 

The error only appears when I add the testmethod.

 

Here's my code:

 

public class Custom_Referral_Task_Controller { 
 
    Id idReferralClass = null;
    public Referral__c ReferralCurrent {get;set;}
    public Task tskNew {get;set;}
    public Contact ReferralDetails {get;set;}
    public Contact ReferrerDetails {get;set;}

    //Pull Data from Current Referral Record
    public Custom_Referral_Task_Controller(ApexPages.StandardController conMain) {
        idReferralClass = conMain.getId();
        ReferralCurrent = [SELECT Id, Contact_Referral_Name__c, Referrer__c FROM Referral__c WHERE Id = :idReferralClass];
        ReferralDetails = [SELECT Id, Name, Account.Name FROM CONTACT WHERE Id = :ReferralCurrent.Referrer__c];
        ReferrerDetails = [SELECT Id, Name, Account.Name FROM CONTACT WHERE Id = :ReferralCurrent.Contact_Referral_Name__c];
        createTaskRecord();
    }

    //Populate Task
    public void createTaskRecord() {
        tskNew = new Task();

        tskNew.OwnerId = vistageconstants.Referral_Accounts_User;
        tskNew.WhoId = ReferralCurrent.Contact_Referral_Name__c;
        tskNew.WhatId = ReferralCurrent.Id;
        tskNew.Subject = 'Referral Validation';
        tskNew.ActivityDate = date.today() + 7;
        tskNew.ReminderDateTime = datetime.now() + 7;
        tskNew.Description = 'Description Here';
    }

    //Save Task
    public PageReference saveAndProceed() {
    
        //insert Task
        insert tskNew;

    // Return URL to Referral Record
        PageReference pf = new PageReference('/' + ReferralCurrent.Id);
        pf.setRedirect(true);
        return pf;
    }

static testMethod void testCustom_Referral_Task_Controller()
{
 
Custom_Referral_Task_Controller c=new Custom_Referral_Task_Controller();
 
Account acct = new Account();
acct.name = 'test';
insert acct;

Contact con = new Contact();
con.lastname = 'testing';
con.firstname = 'hello';
con.email = 'myemail@gmail.com';
con.accountid = acct.id;
insert con;

Referral__c Referral = new Referral__c();
Referral.Referrer__c = con.id;
insert Referral;

c.createTaskRecord();

c.saveAndProceed();

Task t = new task (
subject='Referral Validation',
WhatId = Referral.Id
);

insert t;
    
t = [select Id, subject from Task where id = :t.id];
system.debug(t.subject);
system.assertEquals('Referral Validation',T.Subject);


PageReference ref = new PageReference('/' + Referral.Id);
Test.setCurrentPage(ref);     


}

}

 

Many thanks in advance...

 

 

sfcksfck

Hi,

 

The problem is with this line in the test method:

 

Custom_Referral_Task_Controller c=new Custom_Referral_Task_Controller();

You are trying to create a new Custom_Referral_Task_Controller without passing in any parameters. This is throwing an error 


because you have defined the constructor to require a standard controller as a parameter here:

 

public Custom_Referral_Task_Controller(ApexPages.StandardController conMain) { etc....

 So if you want to create one in your testmethod you will need to create a standard controller and pass that in. 


This was selected as the best answer
KevSnellKevSnell

Thanks I figured this out yesterday and did the following in my test method:

 

ApexPages.StandardController controller = new ApexPages.StandardController(Referral);
Custom_Referral_Task_Controller c = new Custom_Referral_Task_Controller(controller);