Use Case:
Example 10.
Write an Apex trigger named “OpportunityValidationTrigger” that fires before update and enforces the below conditions. If any of the conditions are violated, the trigger should add the appropriate custom error messages to the Opportunity record.
Close Date Validation: Opportunities cannot have a Close Date in the past. If an Opportunity’s Close Date is in the past, display an error message stating, “Opportunity cannot have a Close Date in the past.”
Stage Transition Lock: Opportunities cannot move from “Prospecting” directly to “Closed Won.” If an Opportunity tries to make this transition, show an error message saying, “Opportunity cannot transition directly from Prospecting to Closed Won.”
Minimum Amount for “Closed Won”: Opportunities in the “Closed Won” stage must have an Amount greater than or equal to $10,000.
trigger OpportunityValidationTrigger on Opportunity (before update) {for (Opportunity opp : Trigger.new) {// Close Date Validationif (opp.CloseDate < Date.today()) {opp.addError('Opportunity cannot have a Close Date in the past.');}// Stage Transition Lockif (opp.StageName == 'Closed Won' && Trigger.oldMap.get(opp.Id).StageName == 'Prospecting') {opp.addError('Opportunity cannot transition directly from Prospecting to Closed Won.');}// Minimum Amount for "Closed Won"if (opp.StageName == 'Closed Won' && opp.Amount < 10000) {opp.addError('Opportunity in Closed Won stage must have an Amount greater than or equal to amount 10,000.');}}}
Test Class:
@isTestpublic class OpportunityValidationTriggerTest {@isTest static void testCloseDateValidation() {Opportunity opp = new Opportunity(Name='Test Opportunity', CloseDate=System.today().addDays(-1), StageName='Prospecting', Amount=12000);insert opp;Test.startTest();try {opp.StageName = 'Qualification';update opp;} catch(Exception e) {System.assert(e.getMessage().contains('Opportunity cannot have a Close Date in the past.'));}Test.stopTest();}@isTest static void testStageTransitionLock() {Opportunity opp = new Opportunity(Name='Test Opportunity', CloseDate=System.today().addDays(7), StageName='Prospecting', Amount=8000);insert opp;Test.startTest();try {opp.StageName = 'Closed Won';opp.Amount = 15000;update opp;} catch(Exception e) {System.assert(e.getMessage().contains('Opportunity cannot transition directly from Prospecting to Closed Won.'));}Test.stopTest();}@isTest static void testMinimumAmountForClosedWon() {Opportunity opp = new Opportunity(Name='Test Opportunity', CloseDate=System.today(), StageName='Closed Won', Amount=5000);insert opp;Test.startTest();try {opp.Amount = 8000;update opp;} catch(Exception e) {System.assert(e.getMessage().contains('Opportunity in Closed Won stage must have an Amount greater than or equal to amount 10,000.'));}Test.stopTest();}}
Code Coverage: 100%