I have a unit test that creates a test account and two test contacts. These test contacts are associated with the test account via Id. The test is for an Account trigger that will then grab all associated contacts with the account and do some logic on them. However, the created contacts don't exist when the trigger is fired.
Test file:
@isTest
private class UpdateContactsOnAccountUpdate_Test {
@isTest private static void m1()
{
account a = new account();
a.name = 'Test Account';
insert a;
contact c = new contact();
c.FirstName = 'Test';
c.LastName = 'Test';
c.Phone = '111-111-1111';
c.Email = 'test@test.com';
c.AccountId = a.Id;
insert c;
contact c1 = new contact();
c1.FirstName = 'Test1';
c1.LastName = 'Test1';
c1.Phone = '111-111-1111';
c1.Email = 'test1@test.com';
c1.AccountId = a.Id;
insert c1;
Test.startTest();
Account account = [SELECT Id, Name FROM Account WHERE Id = :a.Id];
account.name = 'New Name';
update account;
Test.stopTest();
}
}
Trigger:
trigger UpdateContactsOnAccountUpdate on Account (after update) {
if(trigger.isupdate)
{
account a1 = trigger.new[0];
List<Contact> ContList = [ select Id, Name from Contact where AccountId = :a1.Id ];
System.debug('Contlist length: '+ContList.size());
for(contact c: ContList){
//logic here
update ContList;
}
}
}
When I run the test, the debug message says "Contlist length: 0" and the for loop is not covered by the test. How do I get the data from my test file to be accessible in the trigger?
Thank you!
test.startTest();
I get both of the newly created contacts. And then in the trigger, I can log the account that fired the trigger, and the Id matches the test one that I made. I will check to see if another trigger is firing too perhaps.for
loop.