2016-08-02 50 views
0

新手在這裏...感謝您的耐心。我感興趣的是寫一個測試類以下的控制器,但不知道從哪裏開始:Apex測試類

public class savecontroller 
{ 
    private final Emp__c emps; 
    public savecontroller(ApexPages.StandardController controller) 
    { 
     this.emps= (Emp__c)controller.getRecord(); 
    } 
    public void autosave() 
    { 
     upsert emps; 
    } 
} 

謝謝

回答

0

你的代碼是有點怪......從這部分:

public savecontroller(ApexPages.StandardController controller) 

它看起來像你的控制器不是一個真正的「控制器」,但更像是Emp__c對象的標準控制器的擴展。我知道,它不會影響你的帖子中的任何東西(除了可能的語義),但(!)它確實會影響你如何編寫測試類。由於這是一個擴展,測試類會是這個樣子:

@isTest 
public class saveconttroller_test { 

    public static Emp__c test_emp; // declaration 

    static { 
     test_emp = new Emp__c(); 
     insert test_emp; //since you have upsert you can leave this out 
    } 

    static testMethod void testsavecotroller() { 

     Test.startTest(); 
     //in the next two lines we contruct standard controller and the extension 
     ApexPages.StandardController sc = new ApexPages.StandardController(test_emp); 
     savecontroller ext = new savecontroller(sc); 
     ext.autosave(); 
     Test.stopTest(); 
    } 
} 

現在,讓我指出一些東西......首先,我敢肯定你知道,測試應涵蓋儘可能多的代碼可能。 SF要求75%,但越接近100%越好。但是,如果你的方法正在做它想要做的事情,你應該總是包含一些東西來斷言。例如,在你的情況,我會改變方法自動保存()這樣的:

public PageReference autosave() 
    { 
     try { 
      upsert emps; 
      return new ApexPages.StandardController(test_emp).view(); 

     } catch(Exception e) { 
      return null;   
     } 
    } 

通過這樣做,您可以在您的測試類System.assertEquals(ref1, ref2);,wher REF1是參考你所期望的(如果upsertion成功,這將成爲test_emp頁面引用),ref2將成爲您實際從測試中獲得的參考。 第二件事是在測試中使用static方法。不管你用這種方法寫什麼,總會在Test.startTest();的調用中執行。

希望這可以幫助你! :) 乾杯,G。