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
SFDC_BigDogSFDC_BigDog 

test class for auto populating trigger

My trigger is working fine. Now I am trying to write a test class and I am stuck. I could not go further. Any insights in completing the test class would be helpful.

TRIGGER DESCRIPTION:
We have a custom object "OrderItem__C". This custom object has a lookup field to standard contact object. It also has a field called "Shipping_customer_number__c".

We have this same field(Shipping_customer_number__c) in contact object too. Now when the user enters a shipping customer number in the order item object, based on the value in the shipping customer number field it should auto populate the contact lookup field.

This is because each contact record has an unique shipping customer number.

TRIGGER:

trigger updatelookupfield on Order_Item__c (before update, before insert) {
    
  
    Set<String> shippingNumbers = new Set<String>();

    for (Order_Item__c collectNumFromOrder : Trigger.new) {
        shippingNumbers.add(collectNumFromOrder.Shipping_Customer_Number__c);
    }

    

    List<Contact> contactList = [SELECT id, Shipping_customer_number__c FROM Contact WHERE Shipping_Customer_Number__c IN :shippingNumbers];

    Map<String, Contact> shippingNumToContactMap = new Map<String, Contact>();

    for (Contact c : contactList) {
        shippingNumToContactMap.put(c.Shipping_customer_number__c, c);
    }

    for (Order_Item__c o : Trigger.new) {
        
          if (o.Shipping_Customer_Number__c != null) {
            o.RSM_Shipping_Contact__c = shippingNumToContactMap.get(o.Shipping_Customer_Number__c).id;
        }
        else {
            o.RSM_Shipping_Contact__c = null;
        }
           
    }
    }
TEST CLASS:
@istest

public class testupdatelookupfield
{
    Static testMethod void insertOrderItem()
    {
        contact c = new contact();
        c.Shipping_Customer_Number__c = '0987654';
        c.FirstName = 'Surekha rani';
        c.LastName = 'Penna';

        try{
            insert c;
            }catch (Exception e){
            System.debug("Error occcured");
            }



        Order_Item__c op = new Order_Item__c();

        op.Name = 'Test Varun Order';
        op.Shipping_Customer_Number__c = '0987654';
        insert op;


            list <contact> shipnum = [select id from contact where Shipping_Customer_Number__c ='0987654' ];
            System.assertEquals(1,shipnum.size());
            map <string,id> shipnummap = new map(string,id);

            for(contact ct: shipnum)
            {
                shipnummap.put(ct.Shipping_Customer_Number__c ,ct);
            }
            list <Order_Item__c > oc = [Select id,RSM_Shipping_Contact__c ,Shipping_Customer_Number__c from Order_Item__c  ];

    }
}


 
Best Answer chosen by SFDC_BigDog
SFDC_BigDogSFDC_BigDog
This is the correct test class for the above trigger.
 
@isTest
public class updatelookupfieldTestclass
{


    @testSetup static void setup() 
      {
                
        contact c = new contact();
        c.Shipping_Customer_Number__c = '0987654';
        c.lastName = 'Surekha';
        insert c;
        
        
        Order_Item__c o = new Order_Item__c();
        o.name = 'ATT';
        o.Shipping_Customer_Number__c = '0987554';
        insert o;

      
 
     }
    Static testMethod void insertOrderItem()
    
      {   
        
        
        Order_Item__c OI=[select id,RSM_Shipping_Contact__c from Order_Item__c where Shipping_Customer_Number__c = '0987554'];
        system.assertequals(OI.RSM_Shipping_Contact__c, null);
      }
        
        Static testMethod void insertOrderItem_Null()
    
      {   
      
        Order_Item__c OI=[select id,RSM_Shipping_Contact__c from Order_Item__c where Shipping_Customer_Number__c = '0987554'];
        Contact c=[select id from contact where Shipping_Customer_Number__c = '0987654'];
       
        OI.Shipping_Customer_Number__c = '0987654';
        update OI;
        
        Order_Item__c OIU=[select id,RSM_Shipping_Contact__c from Order_Item__c where Id=:OI.id];
        system.assertequals(OIU.RSM_Shipping_Contact__c, c.Id);
      }

}

 

All Answers

kaustav goswamikaustav goswami
Please try somthing like this. You may need to add more scenarios in separate methods.
 
@istest

public class testupdatelookupfield
{
    Static testMethod void insertOrderItem()
    {	// create and insert the contact record - this part is correct
        contact c = new contact();
        c.Shipping_Customer_Number__c = '0987654';
        c.FirstName = 'Surekha rani';
        c.LastName = 'Penna';

        try{
            insert c;
			System.debug('#### id of inserted contact #### ' + c.Id); // check the id of the contact
            }catch (Exception e){
				System.debug("Error occcured  " + e.getMessage());
            }

		// create an order item and insert it
        Order_Item__c op = new Order_Item__c();

        op.Name = 'Test Varun Order';
        op.Shipping_Customer_Number__c = '0987654';
        insert op;
		// after insertion the trigger should run and do its job by assigning the lookup field with the conatct id
		list <Order_Item__c > oc = [Select id,RSM_Shipping_Contact__c ,Shipping_Customer_Number__c from Order_Item__c  ];
		System.assertEquals(oc.RSM_Shipping_Contact__c, c.Id); // assert to check that the trigger has updated the value correctly

    }
}

Let me know if there are any questions or problems.

Thanks,
Kaustav
SFDC_BigDogSFDC_BigDog

Hey Kaustav,

This is still not working and getting error. assertion failes.

Also none of my line is covered in code coverage.

 

This is actually my trigger description:
I have written a trigger on custom object Order_Item__c. This object has a custom field Shipping_Number__c. When the user enters value in Shipping_Number__c and clicks save, the contact lookup field will automatically populate with contact record which has same shipping number as the value entered by the user. The trigger is working fine.

kaustav goswamikaustav goswami

Can you please check the debug log to see if the system.debug on line 14 got printed and the result returned by the query on line 26?
If assertion fails that means either the trigger failed to set the value or the query did not return the expected result set.

Also check the debug log to see whether the trigger is firing and how much of it is getting processed.
I will also try and look into the details myself.

Also make sure that while creating the contact and order item records in the test class you are specifying all the required fields. Otherwise there will be a DML exception and the code will fail.

Thanks,
Kaustav
SFDC_BigDogSFDC_BigDog
This is the correct test class for the above trigger.
 
@isTest
public class updatelookupfieldTestclass
{


    @testSetup static void setup() 
      {
                
        contact c = new contact();
        c.Shipping_Customer_Number__c = '0987654';
        c.lastName = 'Surekha';
        insert c;
        
        
        Order_Item__c o = new Order_Item__c();
        o.name = 'ATT';
        o.Shipping_Customer_Number__c = '0987554';
        insert o;

      
 
     }
    Static testMethod void insertOrderItem()
    
      {   
        
        
        Order_Item__c OI=[select id,RSM_Shipping_Contact__c from Order_Item__c where Shipping_Customer_Number__c = '0987554'];
        system.assertequals(OI.RSM_Shipping_Contact__c, null);
      }
        
        Static testMethod void insertOrderItem_Null()
    
      {   
      
        Order_Item__c OI=[select id,RSM_Shipping_Contact__c from Order_Item__c where Shipping_Customer_Number__c = '0987554'];
        Contact c=[select id from contact where Shipping_Customer_Number__c = '0987654'];
       
        OI.Shipping_Customer_Number__c = '0987654';
        update OI;
        
        Order_Item__c OIU=[select id,RSM_Shipping_Contact__c from Order_Item__c where Id=:OI.id];
        system.assertequals(OIU.RSM_Shipping_Contact__c, c.Id);
      }

}

 
This was selected as the best answer