You need to sign in to do that
Don't have an account?
deepak kumar 13
Need Help for test for this trigger
hi all,
i need to write test class for this trigger. Please give some idea
trigger accountTestTrggr on Account (before insert,before update) {
List<Account> accountsWithContacts = [select id, name,(select id,firstname, lastname,Description from Contacts) from Account where Id IN :Trigger.newMap.keySet()];
List<Contact> contactsToUpdate = new List<Contact>{};
for(Account a: accountsWithContacts){
for(Contact c: a.Contacts){
c.Description=c.firstname+c.lastname;
contactsToUpdate.add(c);
}
}
update contactsToUpdate;
}
i need to write test class for this trigger. Please give some idea
trigger accountTestTrggr on Account (before insert,before update) {
List<Account> accountsWithContacts = [select id, name,(select id,firstname, lastname,Description from Contacts) from Account where Id IN :Trigger.newMap.keySet()];
List<Contact> contactsToUpdate = new List<Contact>{};
for(Account a: accountsWithContacts){
for(Contact c: a.Contacts){
c.Description=c.firstname+c.lastname;
contactsToUpdate.add(c);
}
}
update contactsToUpdate;
}
Your trigger should only run in after update trigger as account will not have any contact when account gets inserted.
All Answers
i tried like this below code but getting error as
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, accountTestTrggr: execution of BeforeInsert
caused by: System.NullPointerException: Attempt to de-reference a null object
Trigger.accountTestTrggr: line 2, column 1: []
@isTest
public class accountTestTrggrTclass{
static testmethod void accountTestTrggrTclass(){
Account acc=new Account(Name='TestAcc');
insert acc;
Contact con=[select LastName,FirstName,Description from Contact where id=:acc.id];
con.Description ='Lastfirst';
update con;
contact updatecon=[Select Description from Contact where id=:acc.id];
system.assertEquals('Lastfirst',updatecon.Description );
}
}
Error as : System.QueryException: List has no rows for assignment to SObject
Class.accountTestTrggrTclass.accountTestTrggrTclass: line 13, column 1
@isTest
public class accountTestTrggrTclass{
static testmethod void accountTestTrggrTclass(){
Account acc=new Account(Name='TestAcc');
insert acc;
Contact con= new Contact(LastName='New Con');
insert con;
con.Description ='Lastfirst';
update con;
contact updatecon=[Select Description from Contact where id=:acc.id];
system.assertEquals('Lastfirst',updatecon.Description );
}
}
Your trigger should only run in after update trigger as account will not have any contact when account gets inserted.
direct write the triiger in contact
or
you try to Account write the
after update,after insert After