function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Padmini S 26Padmini S 26 

how to increase code coverage for apex trigger

Hi All,

I have written below trigger.
trigger D2R_DFA_InventoryTrigger on DFA_Inventory__c (before insert, before update) {
    if(trigger.isBefore) {
        if(trigger.isInsert || trigger.isUpdate) {
              for(DFA_Inventory__c inv : trigger.new) {
                 if(inv.Add_Quantity__c != null) {
                    if(inv.Available_Quanity__c == null)
                        inv.Available_Quanity__c = 0;
                    inv.Available_Quanity__c = inv.Add_Quantity__c + inv.Available_Quanity__c;
                    inv.Add_Quantity__c = null;
                }
            }
        }
        
        if(trigger.isInsert) {
           Map<Id, List<DFA_Inventory__c>> mapInvByDFA_Id = new Map<Id, List<DFA_Inventory__c>>();
           for(DFA_Inventory__c inv : trigger.new) {
              mapInvByDFA_Id.put(inv.DFA__c, new List<DFA_Inventory__c>());
            }
            List<DFA_Inventory__c> lstExistingInvs = [SELECT Id, DFA__c, Product__c FROM DFA_Inventory__c
                                                      WHERE DFA__c=:mapInvByDFA_Id.keySet() ];
            
            for( DFA_Inventory__c inv : lstExistingInvs) {
                 if(!mapInvByDFA_Id.containsKey(inv.DFA__c)) {
                    mapInvByDFA_Id.put(inv.DFA__c, new List<DFA_Inventory__c>());
                }
                mapInvByDFA_Id.get(inv.DFA__c).add(inv);
            }
            
            for(DFA_Inventory__c inv : trigger.new) {
                if(mapInvByDFA_Id.containsKey(inv.DFA__c) && mapInvByDFA_Id.get(inv.DFA__c).size() > 0 ) {
                    for(DFA_Inventory__c existingInv : mapInvByDFA_Id.get(inv.DFA__c)) {
                        if(inv.Product__c == existingInv.Product__c) {
                         inv.Product__c.addError('Product already exists in DFA Inventory, Update existing Inventory.');
                        }
                    }
                }
            }
          }
    }
}
Below is the test class
@isTest
public class D2R_DFA_InventoryTriggerTest
{
    @testSetup
    static void Setup()
    {
    
         product2 prod = new product2();
        prod.Name = 'Test Product';
       insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();

        
        PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId,Product2Id = prod.Id, UnitPrice = 10000, IsActive = true );
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
         Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
            
        User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u2;
        
        Account acc1 = new Account(Name='TEST ACCOUNT', RecordTypeId = '012N00000005B9J', Email__c = 'test@gmail.com',Phone = '898789993', ownerId = u2.Id ,Sales_Executive__c = u2.Id);
        insert acc1;  
        
        DFA_Inventory__c dfa = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=50,Product__c = prod.Id,DFA__c = acc1.Id );
        insert dfa;
        
    }
    
        @isTest
        static void InventoryTriggerMethod1()
        {
          DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c ];
        Product2 p = [select id,Name from Product2];
        }
        
         @isTest
        static void InventoryTriggerMethod2()
        {
         Product2 p = [select id,Name from Product2];
        DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c where Product__c = :p.Id];
        try
         {
             df.Product__c = p.Id;
          update df;
       
         }
         
         catch(DMLException e)
        {
                Boolean expectedExceptionThrown =  e.getMessage().contains('Product already exists in DFA Inventory, Update existing Inventory.') ? true : false;
System.AssertEquals(expectedExceptionThrown, true);
        
        }
        
        }
        }

I am getting only 69% code coverage for trigger. I am not able to cover the add error message in test class.could anyone help on this. 

Thanks in Advance.
 
Best Answer chosen by Padmini S 26
Leo10Leo10
Try this
@isTest
public class D2R_DFA_InventoryTriggerTest
{
    @testSetup
    static void Setup()
    {
    
        product2 prod1 = new product2();
        prod1.Name = 'Test Product1';
        insert prod1;
        product2 prod2 = new product2();
        prod2.Name = 'Test Product2';
        insert prod2;
        
        Id pricebookId = Test.getStandardPricebookId();

        
        PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId,Product2Id = prod.Id, UnitPrice = 10000, IsActive = true );
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
         Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
            
        User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u2;
        
        Account acc1 = new Account(Name='TEST ACCOUNT', RecordTypeId = '012N00000005B9J', Email__c = 'test@gmail.com',Phone = '898789993', ownerId = u2.Id ,Sales_Executive__c = u2.Id);
        insert acc1;  
        
        DFA_Inventory__c dfa1 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=50,Product__c = prod1.Id,DFA__c = acc1.Id );
        insert dfa1;

        DFA_Inventory__c dfa2 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=0,Product__c = prod2.Id,DFA__c = acc1.Id );
        insert dfa2;
        
    }
    
        @isTest
        static void InventoryTriggerMethod1()
        {
          DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c ];
        Product2 p = [select id,Name from Product2];
        }
        
         @isTest
        static void InventoryTriggerMethod2()
        {
         Product2 p = [select id,Name from Product2];
        DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c where Product__c = :p.Id];
        try
         {
             df.Product__c = p.Id;
          update df;
       
         }
         
         catch(DMLException e)
        {
                Boolean expectedExceptionThrown =  e.getMessage().contains('Product already exists in DFA Inventory, Update existing Inventory.') ? true : false;
System.AssertEquals(expectedExceptionThrown, true);
        
        }
        
        }
        }

 

All Answers

Lokesh KumarLokesh Kumar
HI Padmini,

Use developer console to open your apex class and then click on left side test coverage to highlight the line considered by your test class.

User-added image

Thanks !
Padmini S 26Padmini S 26
Hi Lokesh,

Thank you for your reply.

User-added image

These lines are not covering in apex trigger. I am not getting how to cover these lines in test class.

 
Lokesh KumarLokesh Kumar
HI,

As you see there are red lines which are not covered in test class so for that you have to add for each loop and same condition just to cover the line because test class covers all the conditions as well.

Thanks !
LBKLBK
Hi Padmini,
Your trigger is a BEFORE trigger.
Line 19 in your trigger (code below) will not return any values in the first call because data is not inserted by the time the the call is made.
List<DFA_Inventory__c> lstExistingInvs = [SELECT Id, DFA__c, Product__c FROM DFA_Inventory__c                                                       WHERE DFA__c=:mapInvByDFA_Id.keySet() ];
I suggest you to add the following code after line 30 in your test class above and run the test again.
DFA_Inventory__c dfa1 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=54,Product__c = prod.Id,DFA__c = acc1.Id );
insert dfa1;
Let me know how it goes.
Padmini S 26Padmini S 26
Hi LBK,

I have tried to add your suggested code in test class. But getting error as 'Variable does not exist: mapInvByDFA_Id' .

Thanks!
LBKLBK
I hope you have added only the following code in the test class.
 
DFA_Inventory__c dfa1 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=54,Product__c = prod.Id,DFA__c = acc1.Id );
	insert dfa1;

Other line is just for your reference
Padmini S 26Padmini S 26
Hi,

I have understood now. I have added below code in test class.
DFA_Inventory__c dfa1 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=54,Product__c = prod.Id,DFA__c = acc1.Id );
        insert dfa1;

But still same code coverage 69%.
Leo10Leo10
Hi
Try this test class
@isTest
public class D2R_DFA_InventoryTriggerTest
{
    @testSetup
    static void Setup()
    {
    
         product2 prod = new product2();
        prod.Name = 'Test Product';
       insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();

        
        PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId,Product2Id = prod.Id, UnitPrice = 10000, IsActive = true );
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
         Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
            
        User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u2;
        
        Account acc1 = new Account(Name='TEST ACCOUNT', RecordTypeId = '012N00000005B9J', Email__c = 'test@gmail.com',Phone = '898789993', ownerId = u2.Id ,Sales_Executive__c = u2.Id);
        insert acc1;  
        
        DFA_Inventory__c dfa1 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=50,Product__c = prod.Id,DFA__c = acc1.Id );
        insert dfa1;

        DFA_Inventory__c dfa2 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=0,Product__c = prod.Id,DFA__c = acc1.Id );
        insert dfa2;
        
    }
    
        @isTest
        static void InventoryTriggerMethod1()
        {
          DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c ];
        Product2 p = [select id,Name from Product2];
        }
        
         @isTest
        static void InventoryTriggerMethod2()
        {
         Product2 p = [select id,Name from Product2];
        DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c where Product__c = :p.Id];
        try
         {
             df.Product__c = p.Id;
          update df;
       
         }
         
         catch(DMLException e)
        {
                Boolean expectedExceptionThrown =  e.getMessage().contains('Product already exists in DFA Inventory, Update existing Inventory.') ? true : false;
System.AssertEquals(expectedExceptionThrown, true);
        
        }
        
        }
        }

Thank you
LBKLBK
You have 3 methods in your test class. Are you running all three of them when you execute the test class?

Also, you have a try catch block in the third method. does that mean that the update statement in the third method won't fire?
Padmini S 26Padmini S 26
Hi,

When i am adding one more DFA inventory in test class, getting error as insertion failed.

System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Product already exists in DFA Inventory, Update existing Inventory.: [Product__c]
LBKLBK
Try this test class.
@isTest
public class D2R_DFA_InventoryTriggerTest
{
    @testSetup
    static void Setup()
    {
    
         product2 prod = new product2();
        prod.Name = 'Test Product';
       insert prod;
        
        Id pricebookId = Test.getStandardPricebookId();

        
        PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId,Product2Id = prod.Id, UnitPrice = 10000, IsActive = true );
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
         Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
            
        User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u2;
        
        Account acc1 = new Account(Name='TEST ACCOUNT', RecordTypeId = '012N00000005B9J', Email__c = 'test@gmail.com',Phone = '898789993', ownerId = u2.Id ,Sales_Executive__c = u2.Id);
        insert acc1;  
        
        DFA_Inventory__c dfa = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=50,Product__c = prod.Id,DFA__c = acc1.Id );
        insert dfa;
        
		dfa.Add_Quantity__c = 10;
		update dfa;
    }
    
}

 
Padmini S 26Padmini S 26
I have tried this giving dfa.Add_Quantity__c = 50; and update dfa in test class. But still code coverage is 69% only.
Leo10Leo10
Try this
@isTest
public class D2R_DFA_InventoryTriggerTest
{
    @testSetup
    static void Setup()
    {
    
        product2 prod1 = new product2();
        prod1.Name = 'Test Product1';
        insert prod1;
        product2 prod2 = new product2();
        prod2.Name = 'Test Product2';
        insert prod2;
        
        Id pricebookId = Test.getStandardPricebookId();

        
        PricebookEntry standardPrice = new PricebookEntry( Pricebook2Id = pricebookId,Product2Id = prod.Id, UnitPrice = 10000, IsActive = true );
        insert standardPrice;
        
        Pricebook2 customPB = new Pricebook2(Name='Custom Pricebook', isActive=true);
        insert customPB;
        
         Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
            
        User u2 = new User(Alias = 'standt1',Country='United Kingdom',Email='demo1@randomdemodomain.com',EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id,TimeZoneSidKey='America/Los_Angeles', UserName='dprobertdemo1@camfed.org');
        insert u2;
        
        Account acc1 = new Account(Name='TEST ACCOUNT', RecordTypeId = '012N00000005B9J', Email__c = 'test@gmail.com',Phone = '898789993', ownerId = u2.Id ,Sales_Executive__c = u2.Id);
        insert acc1;  
        
        DFA_Inventory__c dfa1 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=50,Product__c = prod1.Id,DFA__c = acc1.Id );
        insert dfa1;

        DFA_Inventory__c dfa2 = new DFA_Inventory__c(Add_Quantity__c=4,Available_Quanity__c=0,Product__c = prod2.Id,DFA__c = acc1.Id );
        insert dfa2;
        
    }
    
        @isTest
        static void InventoryTriggerMethod1()
        {
          DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c ];
        Product2 p = [select id,Name from Product2];
        }
        
         @isTest
        static void InventoryTriggerMethod2()
        {
         Product2 p = [select id,Name from Product2];
        DFA_Inventory__c df= [select id,Add_Quantity__c,Available_Quanity__c,Product__c ,DFA__c  from DFA_Inventory__c where Product__c = :p.Id];
        try
         {
             df.Product__c = p.Id;
          update df;
       
         }
         
         catch(DMLException e)
        {
                Boolean expectedExceptionThrown =  e.getMessage().contains('Product already exists in DFA Inventory, Update existing Inventory.') ? true : false;
System.AssertEquals(expectedExceptionThrown, true);
        
        }
        
        }
        }

 
This was selected as the best answer
Padmini S 26Padmini S 26
Hi Leo,

Thank you for your help. while i am trying with your code i got one erro limit has more than one row. So i have limited all queries, then i got 86% code coverage.

Thank you so much.