I have wrote an apex test class but getting 33% code coverage.
Someone, guide me to write an unit test case.
trigger updatePhonenumber on Contact (After insert, After update) {
List<Account> acclist=new List<Account>();
for(Contact con:Trigger.new){
if(con.AccountId != Null && con.Is_Primary__c==true ){
Account acc=new Account();
Id a=con.AccountId;
List<Contact> conlist=[Select id,Is_Primary__c from Contact where Is_Primary__c=true and AccountId=:a];
if(conlist.size()>1){
con.addError('No more primary contacts');
}
acc.Id=con.AccountId;
acc.Phone=con.Phone;
acclist.add(acc);
}
}
update acclist;
}
Hi Pallavi, Try this
@isTest
public class updatePhonenumber_test {
static testMethod void mainTest() {
Account acc=new Account();
acc.Name = 'Test';
insert acc;
Test.startTest();
Contact con = new Contact();
con.LastName = 'AAA';
con.Phone = '1234567890';
con.AccountId = acc.Id;
con.Is_Primary__c = true;
insert con;
List<Account> accList = [select Phone from Account where Id= :acc.Id];
System.assertEquals(accList[0].Phone, con.Phone);
try{
Contact con2 = new Contact();
con2.LastName = 'BBB';
con2.Phone = '567890';
con2.AccountId = acc.Id;
con2.Is_Primary__c = true;
insert con2;
} catch(Exception e) {
system.debug(Logginglevel.INFO,'----> '+ e);
}
Test.stopTest();
}
}