function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Tyler HarrisTyler Harris 

Simulate an Opportunity Save in Test Class?

I've got a Test class that when an Opportunity is "blank saved" the Primary Contact is pulled from the OpportunityContactRole and dropped into a field called "Primary Contact" on the Opportunity. I cannot get any code coverage and the Primary Contact field isn't populating. How can I mimic a save?

Test Class
@isTest

public class TestContactRolePop {

    
    static testMethod void validateOppContact(){
        Test.startTest();
        
        	Account nAcc = new Account(Name='Test Well Opp');
        	insert nAcc;
        system.debug(nAcc);
        	Opportunity nOpp = new Opportunity(Name='Test Well Opp',CloseDate=date.parse('10/31/2015'), Account=nAcc, RecordTypeId='01280000000PyvL', Region__c='NAM', Opportunity_Type__c='Project',StageName='Discovery', Business_Segment__c='Animal ID', Dominant_Technology__c='Edge',Type='One-shot revenue' );
            insert nOpp;
        system.debug(nOpp.Primary_Contact__c);
    		Contact nCon = new Contact(FirstName='Testy',LastName='Test', Account=nAcc, Pricing_Notifications__c='No');
        	insert nCon;
        system.debug(nCon);
        	OpportunityContactRole nOppCon = new OpportunityContactRole(OpportunityId=nOpp.id, IsPrimary=true,ContactId=nCon.Id);
			insert nOppCon;
        system.debug(nOppCon);
            update nOpp;

        system.debug(nOpp.Primary_Contact__c);
system.assertEquals(nOpp.Primary_Contact__c,nCon.Name);
        
    	Test.stopTest();
        
        
    }
}
Trigger
trigger ContactRoleName on Opportunity (before update) {
    
    
    Map<Id,String> mapOppIdWithConLN = new Map<Id,String>();
    
    for(OpportunityContactRole oCR:[select Id, IsPrimary, Contact.Name,Contact.LastName, OpportunityId FROM OpportunityContactRole where opportunityId IN :Trigger.new and isprimary = true]){
        
        mapOppIdWithConLN.put(oCR.OpportunityId, oCR.Contact.Name);
    }

    for(Opportunity opp:Trigger.new){
        if(mapOppIdWithConLN.containsKey(opp.id)){
            opp.Primary_Contact__c = mapOppIdWithConLN.get(opp.id);
        }
        
    }
}