[SalesForce] Passing parameters to Extension Controller for test

I have a Extension Controller which gets back a different set of Opportunities based on the value of HTTP parameter named display sent in. So my code is as such:

public OpportunityListExtension(ApexPages.StandardSetController stdController) {
    // blank constructor
}

public List<Opportunity> getOpportunities() {
    PageReference pageRef = ApexPages.currentPage();
    String display = pageRef.getParameters().get('display');
    String whereclause = '';
    if (display == (LOST)) {
        ...
    } else if (display.equals(INACTIVE)) {
        ...

Based on the the value of display I return different Opportunities. Works great but I need a unit test for this and I am not sure how to pass in the display value to the controller.

Here is my test:

@isTest
public static void testOpportunityListExtension() {
    PageReference pageRef = Page.Opportunities;
    Test.setCurrentPageReference(pageRef);  
    // create an opp
    Opportunity opp = new Opportunity(name='testOpp');
    opp.stageName = 'Closed Won';
    opp.CloseDate = Date.today() - 4;
    List<Opportunity> opps = new List<Opportunity>();
    opps.add(opp);
    insert opps;

    ApexPages.StandardSetController sc = 
             new ApexPages.StandardSetController(new Opportunity[]{});
    //
    // ?????? Not sure how to pass in display value
    OpportunityListExtension ole = new OpportunityListExtension(sc);
    List<Opportunity> oppsFromController = ole.getOpportunities();        

    System.assertEquals(1, oppsFromController.size());
    Opportunity oppportunity = opps.get(0); 
}

Best Answer

The function getParameters() returns a Map<String, String> to which you can add items. In your test you can use something like this:

PageReference pageRef = Page.Opportunities;
pageRef.getParameters().put('display', 'INACTIVE');
Related Topic