+ Start a Discussion

Test trigger for case trigger

Can anyone help with a test class for the below trigger to sort and update cases by email. thx

trigger Case_NewEmailFromImperva on Case (before update) {

// Get a set of all FromAddress from trigger
Set<String> fromAddressSet = new Set<String>();
for (Case c : Trigger.new) {
  if (c.Imperva_Email_Added__c && c.Imperva_Email_Address__c != null) {

// Get a map of email to user/role
Map<String,User> emailUserMap = new Map<String,User>();
List<User> users = [SELECT Id, Username, UserRole.Name FROM User WHERE Username in :fromAddressSet];
for (User u : users) {
  emailUserMap.put(u.Username, u);

// Loop through and change status where needed
for (Case c : Trigger.new) {
  if (c.Imperva_Email_Added__c && c.Imperva_Email_Address__c != null) {
   // If they are not a solution manager, update the status to troubleshooting
   if (!emailUserMap.get(c.Imperva_Email_Address__c).UserRole.Name.contains('Solution Manager')) {
    c.Status = 'Troubleshooting';
   // Either way, always unset the flag and address
   c.Imperva_Email_Added__c = false;
   c.Imperva_Email_Address__c = null;
Phillip SouthernPhillip Southern
Hi, so I havent fully written this out but I've touched on the key parts...and noted where you would need to expand on this.

UserRole ur = new UserRole();
ur.name = 'Test Role';  //anything other than Solution Manager
insert ur;
//If this doesnt work inserting a userrole you can reference an existing role, again anything other than Solution Manager.

User u = new User();
u.email = 'test@test.com;
//**set your additional required fields. (ex. profile)
u.RoleId = ur.Id;
insert u;

Case c = new Case();
c.subject = 'test';
//**set your additional required fields.
insert c;

c.Imperva_Email_Added__c = true;
c.Imperva_Email_Address__c = 'test@test.com';
update c;