Skip to main content
Ashok Reddy 提问于 #Apex
trigger opconrole on Opportunity (after insert) {

Set<Id> accSpecificids = new Set<Id>();

List<OpportunityContactRole> ocrList = new List<OpportunityContactRole>();

Map<id, List<Contact>> accountSpecificContacts = new Map<id, List<Contact>>();

for(Opportunity o: Trigger.New) {

if(o.AccountId != Null)

accSpecificids.add(o.AccountId);

}

for(Contact con: [select id, AccountId from Contact

where AccountId in: accSpecificids]) {

if(accountSpecificContacts.containsKey(con.AccountId))

accountSpecificContacts.put(con.AccountId, new List<Contact>());

accountSpecificContacts.get(con.AccountId).add(con);

for(Opportunity opp: Trigger.New) {

if(accountSpecificContacts.containskey(opp.AccountId)

&& accountSpecificContacts.get(opp.AccountId) != NULL) {

Boolean isFirstContact = true;

for(Contact c: accountSpecificContacts.get(opp.AccountId)) {

OpportunityContactRole ocr = new OpportunityContactRole(ContactId = c.Id,

OpportunityId = opp .id);

if(isFirstContact) {

ocr.IsPrimary = true;

isFirstContact = false;

}

ocrList.add(ocr);

}

}

}

if(ocrList.size() > 0)

insert ocrList;

}

}

Test class:

@isTest

public class opconroleTest {

@isTest

    Public static void opportunity(){

        account acc = new account ();

        acc.name = 'Test';

        insert acc;

        Opportunity opp = new Opportunity();

        opp.name = 'Test opp';

        opp.AccountId = acc.Id;

        opp.CloseDate = system.today();

        opp.StageName = 'Closed won';

        

        insert opp;

        contact con = new contact();

            con.lastname = 'Test con';

            con.AccountId = acc.Id;

           insert con;

        

        OpportunityContactRole conrole = new  OpportunityContactRole();

        conrole.ContactId = con.Id;

        conrole.OpportunityId = opp.Id;

        insert conrole;

        Account ac = [select id,name from account];

        Opportunity op = [select AccountId,name from opportunity];

        contact co = [select AccountId,Lastname from contact];

        System.assertEquals(op.AccountId, ac.Id);

        System.assertEquals(co.AccountId, ac.Id);

        }

}

 
1 个回答
  1. 2022年6月12日 05:39
    Hi,

    Can you please share your running test class screenshot.

    Regard
0/9000