function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rakesh Babu 3Rakesh Babu 3 

Error in Test Code for Apex Trigger

When i execute the below test code:

@isTest
public class TestAfterInsert {   
    static testmethod void AItest(){   
     Account  a1 = new Account (Name = 'After Insert1', Phone = '1234567890');              
        Test.startTest();
        insert a1;
        Test.stopTest();
        Contact c = [Select LastName, Phone from contact where ID = :a1.id];       
        system.assertequals(c.lastname,a1.name);
        system.assertequals(c.phone,a1.phone);      
       }
     }

for below trigger :

trigger AfterInsert on Account (after insert) {
    List<Contact> cons = new List<Contact>();
    For(account a: trigger.new){       
        contact c = new contact();
        c.AccountId = a.Id;
        c.LastName = a.Name;
        c.Phone = a.Phone;       
        cons.add(c); 
    }
    insert cons;       
    }

I am receiving "System.QueryException: List has no rows for assignment to SObject"  error. Can someone please help me out to resolve the error?
 
George AdamsGeorge Adams
Replace this:
Contact c = [Select LastName, Phone from contact where ID = :a1.id];
With this:
Contact c = [Select LastName, Phone from contact where AccountId = :a1.id];
The error is because the query returns no rows, since no contact Id will be identical to the account Id.
VineetKumarVineetKumar
For your test class.
Create a Contact Record as well, associate the contact to the Account, by popupalting the AccountId field on the contact and updating it and use the above query suggested by George in your code.
sailee handesailee hande
Hi Rakesh Babu 3,

Try this :

@isTest
public class TestAfterInsert {
     static testmethod void AItest(){   
     Account  a1 = new Account (Name = 'After Insert1', Phone = '1234567890');              
        Test.startTest();
        insert a1;
        Test.stopTest();
        Contact c = [Select LastName, Phone from contact where AccountID = :a1.id];       
        system.assertequals(c.lastname,a1.name);
        system.assertequals(c.phone,a1.phone);      
       }

}

Thanks.