2016-08-02 49 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。