2017-07-25 44 views
0

我創建了一個觸發器,它調用一個未來的類來向第三方url發出http callout,在此處everthing正常工作,但測試類沒有覆蓋機會字段IsWon &關閉了。在測試類中需要做什麼修改才能使代碼覆蓋率至少達到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); 
} 
} 

//未來觸發類未來的方法,其中我卡觸發

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

    } 
} 

回答

1

您的測試班將必須完成以下操作才能完成所有觸發:

注意,這僅僅是一個辦法做到這一點,你可以做一些不同的方法

  • 創建一個新的機會
  • 更新的機會,一些狀態這是「打開」
  • 創建一個新的機會
  • 更新的機會,關閉/失去
  • 創建一個新的機會
  • 更新機會關閉/韓元

如果你問我,這創造了一個機會,然後TestDataFactory功能,它更新到指定的狀態將是有益的:

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

然後,您可以調用一次那家工廠,每狀態你想在你的測試課中檢查以覆蓋觸發器。

+0

在您爲編輯測試類而進行的編輯中,您只需重複觸發器中if/else語句中調用的每個狀態的機會創建和更新。 – pburns1587