You need to sign in to do that
Don't have an account?

test class for trigger on contact object
Hi Dev's
trigger onecontactforoneaccount on Contact (before insert,before update) {
if(Trigger.isInsert || Trigger.isUpdate){
for(Contact con : Trigger.New){
for(Contact c : [Select id,accountid from contact]){
if(con.accountid == c.accountid && con.accountid != Trigger.oldmap.get(con.id).accountid){
Trigger.oldmap.get(con.id).addError('Duplicate account id');
}
}
}
}
}
Regards
Lakshmi
trigger onecontactforoneaccount on Contact (before insert,before update) {
if(Trigger.isInsert || Trigger.isUpdate){
for(Contact con : Trigger.New){
for(Contact c : [Select id,accountid from contact]){
if(con.accountid == c.accountid && con.accountid != Trigger.oldmap.get(con.id).accountid){
Trigger.oldmap.get(con.id).addError('Duplicate account id');
}
}
}
}
}
Regards
Lakshmi
I have writtern test class, but it was not covered 100%.
Please find below code...
@isTest
private class TestOnecontactforoneaccount {
static testMethod void testOneCon(){
Account a = new Account(name='test acc',phone='9494146144');
insert a;
Account a2 = new Account(name='test acc 2',phone='9494146144');
insert a2;
Contact con = new Contact(accountid=a.id,lastname='test con',email='lnarasimha823@gmail.com');
insert con;
Contact con2 = new Contact(accountid=a.id,lastname='test con2',email='lnarasimha823@gmail.com');
Test.startTest();
try{
insert con2;
}
catch(Exception e){
system.debug('Duplicate Account Id');
}
Test.stopTest();
}
}
Regards
Lakshmi
The code does'nt covers the test data. Because Trigger.oldmap context variable is available in update and delete triggers. So i have just updated a new value with the previous value.
The below is my code, negativeTest() is what i have cerated. Please let us know if it does'nt works.
Regards,
Vivek
Try below code. It will cover 100 % :)
Let me know if this helps.
Thanks,
Amit Singh.
Thanks for your reply.
Both code working fine.
Regards
Lakshmi.
Mark as best answer if your issue has been resolved :)
Thanks,
Amit