0

I am facing difficulty in passing parameters to apex method from test method. In apex method, I am getting parameters from my VF page.

Example of Apex Method:

public PageReference create_contact() 
{
        String callfrom = System.currentPageReference().getParameters().get('callfrom');
        
        Contact newCon = new Contact(lastname = 'Anonymous', phone = callfrom);  
        insert newCon;
        
        return null;
}

My Test method:

static testMethod void testmatchingcontactController()
{
        test.startTest();
        matching_contacts mc = new matching_contacts();
        mc.create_contact();
        test.stopTest();
}

On running test method, I get an error that "Argument cannot be null" because the parameter callfrom in apex code is provided by Visualforce page in application. I don't know how can I pass it from test method.

Please help if you know solution to this problem.

3

In your test method you can do e.g. this:

Test.setCurrentPage(Page.YourPageName);
System.currentPageReference().getParameters().put('callfrom', 'yourvalue');

essentially simulating the missing page so the test can be 100% in Apex.

4
  • In Page.YourPageName I will need to provide the name of VF page? – Badar Dec 11 '20 at 13:46
  • That method accepts a PageReference and the Apex compiler automatically generates that for you under the Page symbol for all your Visualforce pages. So yes, substitute your own page name. – Keith C Dec 11 '20 at 13:48
  • So my VisualForce Page is named as dashboard. I have tried Test.setCurrentPage(Page.dashboard); ApexPages.currentPageReference().getParameters().put('callfrom', '2209');. But I get an error Method does not exist or incorrect signature: void currentPageReference() from the type ApexPages. Could you please identify what's wrong here? – Badar Dec 11 '20 at 13:55
  • @Badar My bad; it should be as you had it System.currentPageReference(). I've changed above. – Keith C Dec 11 '20 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.