You need to sign in to do that
Don't have an account?
Really basic Trigger Test Help
I'm brand new to Apex and I'm working on my first trigger, pasted below. Through manual testing, I know that it works--however, i'm not quite sure how to create test code for it (my attempt is also pasted below).
Any help would be appreciated, and thank you!
Trigger code:
trigger SpouseTrigger on Contact (before insert) { List<Contact> cons = new List<Contact>(); List<Contact> consToInsert = new List<Contact>(); for(Contact c:trigger.new){ if(c.Sig_Other_First_Name__c != null && c.Sig_Other_Last_Name__c != null){ cons.add(c); } } for(Contact c: cons){ Contact newCon = new Contact(); newCon.FirstName = c.Sig_Other_First_Name__c; newCon.LastName = c.Sig_Other_Last_Name__c; newCon.AccountId = c.AccountId; consToInsert.add(newCon); } insert consToInsert; }
This trigger checks to see if two fields (Sig_Other_First_Name and Sig_Other_Last_Name) are filled in, and if they are, creates a new contact record. The contact record uses the First_Name as the First Name and the Last_Name as the last, and puts the contact within the same account as the original contact.
My attempt at a test:
@istest private class SpouseTriggerTest { static TestMethod void Test1_TestInsertContact() { Contact testC1 = new Contact(Text(80)='Test1 Contact', Sig_Other_First_Name__c='John', Sig_Other_Last_Name__c='Smith'); insert testC1; //pull the account info for that contact Contact SecContact = [SELECT cv__Contact__c FROM Account WHERE Id = :testc1.id]; //verify that the insert updated by creating another contact as in the trigger System.assertEquals(testC1.account, SecContact.account); } }
I know this test is really awful but I don't even know where to start! So again, any help at all would be appreciated. Thank you!!
Hi Ali,
Some errors that I spot:
Text(80) doesn't look like a valid field name.
You can't assign a query to Account object to a Contact object, can you?
Anyway, the test class should make sure that the trigger is working as expected. So it should check if the second contact's firstname, lastname and accountid match the first contact's sig other first name, sig other last name and accountid respectively.
I would write something like this:
Hengky
All Answers
Hi Ali,
Some errors that I spot:
Text(80) doesn't look like a valid field name.
You can't assign a query to Account object to a Contact object, can you?
Anyway, the test class should make sure that the trigger is working as expected. So it should check if the second contact's firstname, lastname and accountid match the first contact's sig other first name, sig other last name and accountid respectively.
I would write something like this:
Hengky
Your example was perfect! I didn't get any errors--thank you so much!
(I also added 3 additional scenarios to cover my code 100%).
Thanks again!