如何从顶点测试引用 PageReference 方法 class

How to refer PageReference method from apex test class

我是 apex 的新手,我创建了一个按钮来通过视觉力页面调用 apex class。 这是我的视觉力页面代码。

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

这是我的顶点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;
      }
}

我想创建测试 class。 我不知道如何从测试 class. 引用 PageReference autoRun() 方法class。

您需要为插入的机会配置 StandardController。然后通过StandardController传递给构造函数,然后再调用方法进行测试。

例如

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);

}