1

我正在研究一个触发器/测试类,但我不知道如何让测试类工作。我知道我需要更新使用触发器的机会,但我不确定如何以及如何验证我的触发器是否正常工作。

扳机:

trigger add_primary_advisor on Opportunity(before update) {
for(Opportunity o: Trigger.new){    

     if (o.IsClosed && !Trigger.oldMap.get(o.id).IsClosed) {
       OpportunityContactRole contactRole =
            [select ContactID from OpportunityContactRole where IsPrimary = true and OpportunityId = :o.id];
       if (contactRole != null) {
         o.Primary_Advisor__c=contactRole.ContactID;
       }
     }
   }    
}

测试类:

@isTest
private class primary_advisor_test {
    static testMethod void primary_advisor(){
    Opportunity opp = new Opportunity(Name='test opp', StageName='stage', Probability = 95, CloseDate=system.today());
    insert opp;


update opp; 

}

}

4

2 回答 2

0

问题是您在调用更新之前没有更改任何字段试试这个

opp.Probability  = 90;
update opp;
于 2013-07-08T19:45:07.053 回答
0

在进入测试类的解决方案之前,我想指出触发器没有被构建,因为你的 for 循环中有一个 SOQL 查询,这不是最佳实践。

我不知道opportunityContactRole 对象的确切功能,我只是假设它是一个包含联系人ID 和opportunityID 的对象,或多或少像一个联结对象。

@isTest
private class primary_advisor_test {
  static testMethod void primary_advisor(){
  //Create a contact that will be added to the opportunityCOntactRole.
  contact con = new contact(name='testCon');// add all the required field as per your org settings
  insert Con;
  Opportunity opp = new Opportunity(Name='test opp', StageName='stage', Probability = 95, CloseDate=system.today());
  insert opp;
  //Create the opporunityContactRole.
  opportunityCOntactRole oppCOn = new new opportunityCOntactRole(OpportunityId=opp.id, contactId= con.Id, isPrimary=true);
   insert oppCon;
   //update the opportunity so that it is closed and enters the if conditon in your trigger.
   opp.stageName='Closed';


   update opp; 

  }
}
于 2013-07-09T08:26:17.567 回答