You need to sign in to do that
Don't have an account?
ankitsrivastav7771.3911494159052937E12
Need Help Writing Test Class for Trigger Avoiding Duplicate Account
trigger AccountDuplicatePreventer on Account(before insert,before update)
{
Set<String> vSetNewPersonEmail = new Set<String>();
Map<String, Account> OldAccounttMap = new Map<String, Account>();
Map<String, Account> NewAccountMap = new Map<String, Account>();
for(Account a: trigger.new){
NewAccountMap.put(a.PersonEmail,a);
}
List<Account> vLstOldAccount = [SELECT Id,name,PersonEmail FROM Account WHERE isPersonAccount = true AND PersonEmail in: NewAccountMap.keyset() ];
system.debug('this is test'+vLstOldAccount );
If(vLstOldAccount.size()>0){
for(Account b: vLstOldAccount){
OldAccounttMap.put(b.PersonEmail,b);
}
for(Account a: trigger.new){
a.PersonEmail.adderror('There is already another Account with the same PersonEmail.' +
'Refer: <a href=\'/' +
OldAccounttMap.get(a.PersonEmail) + '\'>' +
OldAccounttMap.get(a.PersonEmail).Name + '</a>',
FALSE
);
}
}
Test Class
@isTest(SeeAllData=True)
Public Class TestcontactDuplicatePreventer
{
Static testMethod Void contactDuplicatePreventer()
{
Account ac= new Account();
ac.LastName='xyz';
ac.Email__c='test@sales.com';
ac.PersonEmail='test@ibm.com';
}
}
{
Set<String> vSetNewPersonEmail = new Set<String>();
Map<String, Account> OldAccounttMap = new Map<String, Account>();
Map<String, Account> NewAccountMap = new Map<String, Account>();
for(Account a: trigger.new){
NewAccountMap.put(a.PersonEmail,a);
}
List<Account> vLstOldAccount = [SELECT Id,name,PersonEmail FROM Account WHERE isPersonAccount = true AND PersonEmail in: NewAccountMap.keyset() ];
system.debug('this is test'+vLstOldAccount );
If(vLstOldAccount.size()>0){
for(Account b: vLstOldAccount){
OldAccounttMap.put(b.PersonEmail,b);
}
for(Account a: trigger.new){
a.PersonEmail.adderror('There is already another Account with the same PersonEmail.' +
'Refer: <a href=\'/' +
OldAccounttMap.get(a.PersonEmail) + '\'>' +
OldAccounttMap.get(a.PersonEmail).Name + '</a>',
FALSE
);
}
}
Test Class
@isTest(SeeAllData=True)
Public Class TestcontactDuplicatePreventer
{
Static testMethod Void contactDuplicatePreventer()
{
Account ac= new Account();
ac.LastName='xyz';
ac.Email__c='test@sales.com';
ac.PersonEmail='test@ibm.com';
}
}
Try test mehod like this
All Answers
I recomend you to remove (SeeAllData=True) and create first Account manually in test.
The second(duplicated account) insert wrap into try-catch block and Assert that code reached catch statement.
Hope it helps.
Regards,
Denis Vakulishin
Try test mehod like this