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
Dilyan DimitrovDilyan Dimitrov 

Non static mehtod invocation in static test method

Hello,

I have a controller class where I have a non static field leadObj which is initialized in constructor with parameter:
// Constructor
public LeadToMerchantController(ApexPages.StandardController controller) {    
    objLead = (Lead)controller.getRecord();
    System.debug('objLead ' + objLead.Id);   
}

I have two non static methods where the leadObj is used and from two testMethods in a TestClass I want to start and test the two methods. Here is how the testMetdhods are implemented:
 
static testMethod void testLeadStatusExistingDeal() {
    Test.startTest();
    Lead leadObj = new Lead(LastName = 'test', Currency__c = 'USD', Company ='test', Monthly_Volume__c= '1234', Phone='1423542452', Website='www.google.com', Status = '0% Dead Lead');
    System.debug('leadObj ' + leadObj);
    String leadStatusExistingDeal = LeadToMerchantController.leadStatusExistingDeal(leadObj);
    System.debug('leadStatusExistingDeal ' + leadStatusExistingDeal);
    Test.stopTest();
}

static testMethod void testConvertOrRedirect(){
    Test.startTest();
    LeadToMerchantController.convertOrRedirect();
    Test.stopTest();
}

the two methods in the LeadToMerchantController class can not be invoked directly(calssName.methodName) because they are not static.

It is not possible to make an object from this LeadToMerchantController class because the constructor has a specific parameter 
public LeadToMerchantController(ApexPages.StandardController controller)
and it is not clear what to pass for parameter.

How can I invoke from the test method the other method 
LeadToMerchantController.convertOrRedirect();
which has to be tested?

 
Tarun J.Tarun J.
Hello Dilyan,

Try this:
 
static testMethod void testLeadStatusExistingDeal() {
    Test.startTest();
    Lead leadObj = new Lead(LastName = 'test', Currency__c = 'USD', Company ='test', Monthly_Volume__c= '1234', Phone='1423542452', Website='www.google.com', Status = '0% Dead Lead');		
    System.debug('leadObj ' + leadObj);

	Insert leadObj;				//Insert Test Lead record.

	//Initialize controller
	ApexPages.StandardController sc = new ApexPages.StandardController(leadObj);		
    LeadToMerchantController testLeadToMer = new LeadToMerchantController(sc);

    PageReference pageRef = Page.<provide name of your page>;		//For e.g.: Page.HelloWorld
	Test.setCurrentPage(pageRef);			//Set Current Page

	testLeadToMer.convertOrRedirect();		//Call all your methods like this.
    Test.stopTest();
}

-Thanks,
TK

PS: Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.
Jonathan Meltzer 14Jonathan Meltzer 14
This solution worked for me.  Much appreciated!