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.
I am new in writing test classes and I am unable to write test class for my trigger. I am posting the code. Any insights would be helpful.
Trigger:
trigger updatelookupfield on Order_Item__c (before update, before insert) {
Set<String> shippingNumbers = new Set<String>();
for (Order_Item__c collectNumFromOrder : Trigger.new) {
shippingNumber.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';
insert c;
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 ];
}
}