+ Start a Discussion
Travis WrightTravis Wright 

TEST Class: Can I use a button action to create an opp from a contact record?

So I am writing a test class that is covering the below trigger but it only works if it is created from the New Opportunity button when it is clicked. I am not sure if it is possible but in my test class if I create a contact can I call the button action and check the results from the opportunity is created and inserted? I have not overrode the button or anything, I can't find any information on this. 

trigger fillLeadSource on Opportunity (before update) {
   Set<Id> oppsToFill = new Set<Id>();
    for(Opportunity o : trigger.new){
        if(o.LeadSource == null) {
            oppsToFill.add(o.Id);
        }
    }

    // Now we'll select all possible contacts wasting only 1 query.
    if(!oppsToFill.isEmpty()){
        List<OpportunityContactRole> roles = [SELECT OpportunityId, Contact.Name, Contact.LeadSource, Contact.Lead_Source_Name__c
            FROM OpportunityContactRole
            WHERE isPrimary = true AND Contact.LeadSource != null AND OpportunityId IN :oppsToFill];

        if(!roles.isEmpty()){
            for(OpportunityContactRole ocr : roles){
                Opportunity oppToBeFilled = trigger.newMap.get(ocr.OpportunityId);
                System.debug('Changing lead source on ' + oppToBeFilled.Name + ' from ' + oppToBeFilled.LeadSource + ' to ' + ocr.Contact.LeadSource + ' (thx to ' + ocr.Contact.Name + ' being the Primary Contact).');
                oppToBeFilled.LeadSource = ocr.Contact.LeadSource;
              }
        }
    }
}
Best Answer chosen by Travis Wright
Balaji BondarBalaji Bondar
Hi Travis,

Trigger test class will not fire from the UI actions such as button clicks.Trigger will be validated for test class run based on the data you have created in the test class.Make sure that you are creating data so that it will satisfy the trigger conditions.