Before deploying a trigger, write unit tests to perform the actions that fire the trigger and verify expected results.
Let’s test a trigger that we worked with earlier in the Writing Apex Triggers unit. If an account record has related opportunities, the AccountDeletion trigger prevents the record’s deletion.
Apex Trigger
trigger AccountDeletion on Account (before delete) {
// Prevent the deletion of accounts if they have related opportunities.
for (Account a : [SELECT Id FROM Account
WHERE Id IN (SELECT AccountId FROM Opportunity) AND
Id IN :Trigger.old]) {
Trigger.oldMap.get(a.Id).addError(
'Cannot delete account with related opportunities.');
}
}
Apex Test Class:
@isTest
private class TestAccountDeletion {
@isTest static void TestDeleteAccountWithOneOpportunity() {
// Test data setup
// Create an account with an opportunity, and then try to delete it
Account acct = new Account(Name='Test Account');
insert acct;
Opportunity opp = new Opportunity(Name=acct.Name + ' Opportunity',
StageName='Prospecting',
CloseDate=System.today().addMonths(1),
AccountId=acct.Id);
insert opp;
// Perform test
Test.startTest();
Database.DeleteResult result = Database.delete(acct, false);
Test.stopTest();
// Verify
// In this case the deletion should have been stopped by the trigger,
// so verify that we got back an error.
System.assert(!result.isSuccess());
System.assert(result.getErrors().size() > 0);
System.assertEquals('Cannot delete account with related opportunities.',
result.getErrors()[0].getMessage());
}
}
Another Example Scenario:
Apex Trigger:
rigger accountAfterInsert on Account (after insert) {
string managerId= [Select Id, ManagerId FROM User WHERE Id = :userInfo.getUserId()].ManagerId;
for(Account acc: trigger.New){
AccountShare accShare = new AccountShare();
accShare .ParentId = acc.Id;
accShare .UserOrGroupId = managerId;
accShare .AccessLevel = 'EDIT';
accShare .RowCause = Schema.accountShare.RowCause.Manual;
}
}
January 02, 2021 at 12:40PM Click here for more details...
=============================
The original post is available in Jayakrishna Ganjikunta by jayakrishnasfdc
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================
Post a Comment