2013-07-08 35 views
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; 

} 

}

回答

0

去之前进入测试类的解决方案我想指出触发器没有建立,因为你有一个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; 

    } 
} 
0

问题是你没有调用更新之前更改了任何领域试试这个

opp.Probability = 90; 
update opp;