How to Write test class for trigger:
Here is the example to write a unit test method for a simple Apex Trigger.
Following trigger is executed whenever an account is created and creates sharing to the manager to that record.
Apex Trigger Code:
trigger 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; } }
// Unit Test for above Trigger
@isTest private class AccountTriggersTest{ private static testmethod void accountTriggersTest(){ Account acc = new Account(); acc.name = ‘NewAccount’; acc.address = ‘USA’; insert acc; } }