-3

Can any one help me to write test class for below mentioned code

trigger ContactTriggerWithList1 on Contact (before insert) {

List<Account> lacc = [select Id, Name, Type from Account];

for(Contact c :trigger.New)
{
    
    for(Account a :lacc)
    {
        if(c.AccountId==a.Id)
        {
            c.Type__c=a.Type;
        }
    }
}

}

Test Class********** @isTest public class ContactTriggerWithList1_TriggerHandler {

@isTest

static void test_insertContact()
{
    Account a = new Account(name='TestAccount', Type='Prospect');
    insert a;
    
    Contact c = new Contact();
    c.LastName= 'TestContact';
    if(c.AccountId==a.Id)
    {
      c.Type__c=a.Type;
    }
   
    insert c;
    System.assertEquals(c.Type__c, a.Type);
 

}

}

This test class is giving 85% coverage. Can anyone help here? It is not covering C.Type__c == a.Type portion. Even though, I have written System.assert method as well.

1

In test methods, you're generally responsible for setting up the test data appropriately.

You're not setting the AccountId on your test contact in your test method, so when you reach the if(c.AccountId == a.Id) part in your trigger, it never evaluates to true, you never execute that code in the test, and thus you don't get coverage for it.


Your test method should not have the following lines in it:

if(c.AccountId==a.Id)
{
    c.Type__c=a.Type;
}

You want the thing you're testing, your trigger, to do that update (if it's appropriate to do so). Having that code directly in your test method defeats the purpose of the test (it doesn't get executed as-is, but it would be if you updated your test setup to be correct).


While it's not causing an issue, the nested loop where you check if(a.Id == b.Id) is extraordinarily wasteful. You should store the result of your account query in a Map<Id, Account>, and then check if the contact's accountId exists in the map. This removes the need for the nested loop, and turns your O(n^2) solution into a much better O(2n) solution.

| improve this answer | |
  • Thanks for detail explanation. It really helped me. I forgot that part( to set up the account Id on contact record). I removed those lines and now it is giving 100% coverage. – hakim upadhyay Jun 29 at 20:12
  • @hakimupadhyay Coverage is fine, but don't forget that the real utility of writing tests is in the assertions you make. You can have 100% coverage on a class/method that returns "5" when you ask "what is 2 + 2?", but that doesn't change the fact that the code is wrong. You should strive not for coverage, but to test many different paths of execution in your code. Assertions ensure your results are what you expect, testing many paths ensures your code is robust, and together they automatically lead to high coverage. – Derek F Jun 30 at 15:33
  • Definitely Derek. Thanks for providing the valuable suggestion – hakim upadhyay Jun 30 at 17:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.