我正在研究触发器/测试类,我无法弄清楚如何使测试类工作。我知道我需要更新我使用触发器的机会,但我不知道如何以及如何验证我的触发器是否正常工作。
触发:
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 :(得分:0)
问题是你在调用update之前没有更改任何字段试试这个
opp.Probability = 90;
update opp;
答案 1 :(得分: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;
}
}