I wanted to write test class for Triger which insert contact on user Insertion. So I am writing test class to check whether new created contact is related to that user or not but Im receiving error. sharing my trigger and the error is in a test class. can somebody please help me understand to get rid of this error.
Trigger:
trigger BeforeInsertUseronCondeleteTrigger on User (before Insert , after Insert) {
if(Trigger.isBefore && Trigger.isInsert) {
BeforeInsertUseronCondeleteHandler.PreventContactAddition(Trigger.new);
}
if(Trigger.isAfter && Trigger.isInsert) {
BeforeInsertUseronCondeleteHandler.PreventContactAddition(Trigger.new);
}
}
Handler:
public class BeforeInsertUseronCondeleteHandler {
public static void PreventContactAddition(List<User> newList){
Set<String> emailSet = new Set<String>();
List<Contact> contact = new List<Contact>();
Final String errMsg = 'The email already exists on another Record: ';
for( User u : newList ) emailSet.add( u.Email );
Map< String, Id > duplicateContactMap = new Map< String, Id >();
for( Contact c : [select Id, Email from Contact where Email = :emailSet] )
duplicateContactMap.put( c.Email, c.Id );
for( User u : newList ){
Id duplicateContactId = duplicateContactMap.get( u.Email );
if( duplicateContactId != null ){
u.addError( errMsg + duplicateContactId );
}
else if( Trigger.isAfter && Trigger.isInsert) {
Contact con = new Contact(LastName = u.LastName,OwnerId=u.Id, Email=u.Email);
contact.add(con);
}
}
Insert contact;
}
}
Test class:
@isTest
public class BeforeInsertUseronCondeleteTriggerTest {
@testSetup static void setup() {
List<User> lstUser= new List<User>();
Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
// Creating common test User
User u = new User();
u.Alias = 'ttgtt';
u.Email = '[email protected]';
u.EmailEncodingKey = 'UTF-8';
u.LastName = 'Test';
u.LanguageLocaleKey = 'en_US';
u.LocaleSidKey = 'en_US';
u.TimeZoneSidKey='America/Los_Angeles';
u.ProfileId = p.Id;
u.UserName='[email protected]';
lstUser.add(u);
// Creating common test Contacts
List<Contact> lstCon = new List<Contact>();
Contact objCon = new Contact();
objCon.LastName = 'Test1';
objCon.OwnerId = u.Id;
objCon.Email=u.Email;
lstcon.add(objCon);
Insert lstCon;
}
@isTest static void testConOnAcc()
{
User u = [SELECT Id, Email FROM User WHERE UserName='[email protected]' LIMIT 1];
Contact conObj = [SELECT Id, Email, OwnerId FROM Contact WHERE LastName='Test1' AND OwnerId=:u.Id LIMIT 1];
System.runAs(u){
Test.startTest();
System.assertEquals('[email protected]', conObj.Email);
Test.stopTest();
}
}
}
lstUser.add(u);
after this line addinsert lstUser;
and try again.