How to refer PageReference method from apex test class

waqas ali picture waqas ali · Jul 16, 2015 · Viewed 9.4k times · Source

I am new to apex, I have created a button to call the apex class through the visual force page. Here is my visual force page code.

<apex:page standardController="Opportunity" 
extensions="myclass" 
action="{!autoRun}"> 
</apex:page>

Here is my apex class.

public class myclass {
    private final Opportunity o;
    String tmp;

   public myclass(ApexPages.StandardController stdController) {
        this.o = (Opportunity)stdController.getRecord();
    }
    public PageReference autoRun() { 
        String theId = ApexPages.currentPage().getParameters().get('id');

   for (Opportunity o:[select id, name, AccountId,  from Opportunity where id =:theId]) {

                 //Create the Order
                    Order odr = new Order(  
                    OpportunityId=o.id
                    ,AccountId = o.AccountId
                    ,Name = o.Name
                    ,EffectiveDate=Date.today()
                    ,Status='Draft'
                    );
                insert odr;
                tmp=odr.id;             
              }                  
        PageReference pageRef = new PageReference('/' + tmp);  
        pageRef.setRedirect(true);
        return pageRef;
      }
}

I want to create test class. I don't know how to refer PageReference autoRun() method from test class. Guys need help if some one can tell me about test class of this apex class.

Answer

Daniel Ballinger picture Daniel Ballinger · Jul 17, 2015

You will need to configure the StandardController for the inserted Opportunity. Then pass the StandardController to pass to the constructor before calling the method to test.

E.g.

public static testMethod void testAutoRun() {

    Opportunity o = new Opportunity();
    // TODO: Populate required Opportunity fields here
    insert o;

    PageReference pref = Page.YourVisualforcePage;
    pref.getParameters().put('id', o.id);
    Test.setCurrentPage(pref);

    ApexPages.StandardController sc = new ApexPages.StandardController(o);

    myclass mc = new myclass(sc);
    PageReference result = mc.autoRun();
    System.assertNotEquals(null, result);

}