我创建了一个触发器,它调用未来的类来对第三方URL进行http调用,这里的everthing工作正常,但是测试类没有覆盖机会字段IsWon&关闭了。我需要在测试类中进行哪些修改才能使此触发器的代码覆盖率至少达到75%。
// Apex触发器
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();
}
}
答案 0 :(得分:1)
您的测试类必须执行以下操作才能完成所有触发操作:
注意,这只是一种方法,你可以用几种不同的方式做到这一点
如果您问我,创建机会并将其更新为指定状态的TestDataFactory函数会有所帮助:
@isTest
public testOpportunityWithStatusChange(targetStatus){
//do stuff here
};
然后,您可以针对要在测试类中检查的每个状态调用该工厂一次以覆盖触发器。