4

This is My Trigger for finding duplicate for Phone And MobilePhone

trigger duplicate_mobile on Contact (before insert, before update) { Map<String,Contact> mapContact = new Map<String,Contact>(); for(Contact cont :Trigger.new){ if((cont.phone != null ) && (System.Trigger.isInsert) ||(cont.phone != System.trigger.oldmap.get(cont.Id).phone)){ mapcontact.put(cont.phone,cont); } if((cont.MobilePhone!= null) && (system.trigger.isInsert) ||(cont.MobilePhone!= system.trigger.oldmap.get(cont.id).MobilePhone)){ mapcontact.put(cont.MobilePhone,cont); } } for(contact cont :[select phone from contact where phone in:mapcontact.keyset()]){ contact cc = mapcontact.get(cont.phone); cc.phone.adderror('error'); } for(contact con :[select MobilePhone from contact where MobilePhone in:mapcontact.keyset()]){ contact ccc = mapcontact.get(con.MobilePhone); ccc.MobilePhone.adderror('error already no is saved'); } } 

This is my unit test

@isTest //test methos for duplicate_mobile for contact private class test_duplicate_mobile{ static testmethod void dup_phone(){ contact contw = new contact (); contw.lastname = 'tester'; contw.phone = '9999999999'; contw.mobilephone = '8888888888'; insert contw; contact contr = new contact(); contr.lastname='as'; contr.phone = '7777777777'; contr.mobilephone='0000000000'; insert contr; contw.phone = '11111111111'; contw.mobilephone = '8888888887'; update contw; } } 

I am getting 66% code coverage because it is not entering for loops this is snapshot of code coverage

enter image description here

1 Answer 1

4

You're not entering the loop because the queries don't return any records. As far as I can tell, the purpose is to detect duplicate phone numbers, but you're not inserting duplicate phone numbers in your test.

Try adding this to your test:

contact contr = new contact(); contr.lastname='as'; contr.phone = '9999999999'; contr.mobilephone='8888888888'; insert contr; 
2
  • Thanks, for code. Now I am getting 100% test coverage,but it is not passing the method, Error is "System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, error already no is saved: [MobilePhone]" Commented Feb 4, 2014 at 12:21
  • 2
    That's what you wanted right? To test the validation. So enclose the insert I gave you in a try-catch and assert the message. Commented Feb 4, 2014 at 13:59

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.