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
apsullivanapsullivan 

Creating my first test class for a simple trigger

I've written a pretty simple trigger and I was hoping to get a hand with a test class.

 

All my trigger does is stamp the account with the same user lookup value from an opportunity (CF Manager -> Account CF Owner fields).  I'm brand new to Apex so help is always appreciated.  The trigger fires without issue.

 

Here's the trigger:

 

trigger OnAccountOpportunityCFManager on Opportunity (before insert, before update) {
    List<Id> AccountsToUpdate = new List<Id>{}; 
    // Find account to update
    for(Opportunity o: Trigger.new){
        if (o.CF_Manager__c != Null && o.AccountId != Null)  {
            AccountsToUpdate.add(o.AccountId);
        }
    // Pull field data from account
    List<Account> accts = new List<Account>([SELECT Id, Account_CF_Owner__c FROM Account WHERE Id IN :AccountsToUpdate]);
    // Update account    
    for(Account a: accts) {
    a.Account_CF_Owner__c = o.CF_Manager__c;
    update a;
    }
    }
}

 Thanks!

Best Answer chosen by Admin (Salesforce Developers) 
Vinit_KumarVinit_Kumar

Hi Sullivan

 

Try below code :-

 

@IsTest(SeeAllData=true)
public class OnAccountOpportunityCFManager_test{
	static testmethod void MyUnitTest(){
	
		Account acc = new Account(Name='ABC');
		insert acc;
		
		Opportunity opp = new Opportunity(Name='Test opp',CloseDate=system.today(),Stage='Prospecting',AccountId=acc.id,CF_Manager__c=<some value>);//populate //all the mandatory fields to insert a record for Opportunity
		insert opp;
	
	
	}
}

 

All Answers

Vinit_KumarVinit_Kumar

Hi Sullivan

 

Try below code :-

 

@IsTest(SeeAllData=true)
public class OnAccountOpportunityCFManager_test{
	static testmethod void MyUnitTest(){
	
		Account acc = new Account(Name='ABC');
		insert acc;
		
		Opportunity opp = new Opportunity(Name='Test opp',CloseDate=system.today(),Stage='Prospecting',AccountId=acc.id,CF_Manager__c=<some value>);//populate //all the mandatory fields to insert a record for Opportunity
		insert opp;
	
	
	}
}

 

This was selected as the best answer
apsullivanapsullivan

Thanks so much!  This is exactly the start I needed.  With the required fields added, this gave my trigger 100% coverage.  One small note for anyone else that may find this helpful: the field name for Stage is StageName.

 

Again, though, thanks!

Vinit_KumarVinit_Kumar

Happy to help Sullivanand I forgot to put the API name of the field Stage.