0

我创建了一个触发器,它调用一个未来类来对第三方 url 进行 http 标注,这里一切正常,但测试类没有涵盖机会字段 IsWon 和 IsClosed。我需要在测试类中进行哪些修改才能使此触发器的代码覆盖率至少达到 75%。

//顶点触发器

trigger oppTrigger on Opportunity (before update) {

String oppType = '';
for(Opportunity opp : Trigger.new){

if (opp.IsClosed == true){  // closed
  if (opp.IsWon == true){
    oppType = 'Won'; // closed-won
   }else{
    oppType = 'Lost'; // closed-lost
   }
} else { // open
       oppType = 'Open'; 
    }
  // call a method with @future annotation
   futureCls.srvcCallout(opp.id,opp.Amount,oppType); 
 }
}

// 带有future方法的触发器的future类

global class futureCls {
@future(callout=true)
Public static void srvcCallout(String oppId, Decimal oppAmt, String oppType){

     // Create http request
     HttpRequest req = new HttpRequest();
     req.setMethod('POST');
     req.setHeader('Content-Type', 'application/json;charset=UTF-8');     
     req.setEndpoint('https://www.testurl.com/salesforce/opp-change'+'?id='+oppId+'&amt='+oppAmt+'&stage='+oppType);

     // create web service
     Http http = new Http();
      try {
        // Execute web service call here     
        HTTPResponse res = http.send(req);  
        // Debug messages
        System.debug('RESPONSE:'+res.toString());
        System.debug('STATUS:'+res.getStatus());
        System.debug('STATUS_CODE:'+res.getStatusCode());
        System.debug('BODY:'+res.getBody());

        } catch(System.CalloutException e) {
             // Exception handler
             System.debug('Error connecting to Paperless..');
       }   
     }
 }

// 测试我卡住的触发器的类:-

@isTest
private class futureCls_Test {  

 private static testMethod void srvcCallout_Test() {        

    Test.startTest();

    // Unit test to cover trigger update event
    Opportunity opp = new Opportunity(Name='test opp', StageName='stage', Probability = 95, CloseDate=system.today());
    insert opp;
    opp.Amount = 1000;
    opp.StageName = 'Closed/Won';
    update opp;

    // Assign some test values
    String oppId = '1sf2sfs2';
    Decimal oppAmt = 4433.43;
    String oppType = 'Won';

    // Unit test to cover future method
    futureCls.srvcCallout(oppId, oppAmt,oppType);    

    // Unit test to cover http web service
    Test.setMock(HttpCalloutMock.class, new futureClsCalloutMock()); 
    Test.stopTest();

  }
}
4

1 回答 1

1

您的测试类必须执行以下操作才能触发所有触发器:

注意,这只是一种方法,你可以用几种不同的方法

  • 创造新机会
  • 将机会更新为“开放”状态
  • 创造新机会
  • 将机会更新为关闭/丢失
  • 创造新机会
  • 将机会更新为已结束/赢得

如果您问我,创建机会然后将其更新为指定状态的 TestDataFactory 函数会很有帮助:

@isTest
public testOpportunityWithStatusChange(targetStatus){
    //do stuff here
};

然后,您可以为要在测试类中检查的每个状态调用该工厂一次以覆盖触发器。

于 2017-07-25T20:15:47.173 回答