You need to sign in to do that
Don't have an account?
Test class to create and update contact on acc creation
Hello
Im new to apex and I have written a code to create a contact on account creation and its updation when account is updated.
the code is as follows:
trigger CreateAccountContact on Account (after insert,after update){
if(Trigger.isInsert){
List<Contact> ct = new List <Contact>();
for(Account acc : trigger.new){
Contact c = new Contact(LastName = acc.name,
AccountId=acc.id,
Fax=acc.Fax,
Phone=acc.Phone,
Email=acc.Email__c);
ct.add(c);
}
if(!ct.isEmpty())
{insert ct; }
}
else{
Set<Id> acctIds = new Set<Id>();
List<Contact> cntsload = new List<Contact>();
//Map<Id, Account> contactmap = new Map<Id, Account>{};
for(Account acc : trigger.new){
acctIds.add(acc.id);
//contactmap.put(acc.id, acc);
}
cntsload = [select AccountId,Name
from Contact
where AccountId in :acctIds];
for (Contact cnt :cntsload ){
cnt.LastName=Trigger.newMap.get(cnt.AccountId).Name;
cnt.Fax=Trigger.newMap.get(cnt.AccountId).Fax;
cnt.Phone=Trigger.newMap.get(cnt.AccountId).Phone;
cnt.Email=Trigger.newMap.get(cnt.AccountId).Email__c;
}
if(!cntsload.isEmpty()){
update cntsload;
}
}
}
I have written a test class but it throws an exception of:System has no rows for assignment to Sobject.
@isTest
public class TestCreateAccountContact{
static testmethod void TestgetAgentInfoCon()
{
Account testacc=new Account();
testacc.name='tstacc';
testacc.Email__c='tst@aol.com';
testacc.Customer_No__c='123';
insert testacc;
Account act=[select id,name,email__c from Account where name=:'tstacc'];
//Agent__c dumAgnt=[Select id,Name from Agent__c where Name='Dummy Agent'];
Test.startTest();
Contact ct=[select id,LastName,email,accountID from contact where accountID=:act.id];
System.assertEquals('tstacc',ct.LastName);
System.AssertEquals('tst@aol.com',ct.Email);
Test.stopTest();
}}
Please suggest changes to either of the codes to resolve error.
Thanks!
It looks like there is an issue with your query. Either the Account or the Contact is not returning any records. You have two options:
1. Create a new Account and new Contact in your test method
OR
2. Turn on "See all Data" (@isTest (SeeAllData=true)).
The first option is recommended as you should never rely on actual data in your test methods.
Hey sfdc dev
I think your code is this much bigger, and then u just need to first insert an Account records and then update that record in test class
trigger CreateAccountContact on Account (after insert,after update){
if(Trigger.isAfter) {
if(Trigger.isInsert || Trigger.isUpdate){
List<Contact> ct = new List <Contact>();
for(Account acc : trigger.new){
Contact c = new Contact(LastName = acc.name,
AccountId=acc.id,
Fax=acc.Fax,
Phone=acc.Phone,
Email=acc.Email__c);
ct.add(c);
}
}
}
if(!ct.isEmpty()) {
insert ct;
}
}