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
wadams2010wadams2010 

Understanding 'List has no rows for assignment to SObject' in a trigger creating new record on custom object

I'm having an issue with my Apex Test Class from a trigger. I've used the trigger multiple times in my sandbox but when I try to test it out it fails. The reason for the failure is 'System.QueryException: List has no rows for assignment to SObject' which I have tried to look up but there are so many answers and they don't apply to my certain case. Tried it multiple ways and I am wondering if anybody here has a good answer.

I have two objects, Implementation (custom) and Opportunity. The trigger fires when an Opportunity is set to 'Closed Won'. Below is the trigger:

trigger CreateImplementation on Opportunity (after update) {

    List<Id> opps = new List<Id>();

    for ( Opportunity opp : Trigger.new ){


        if((opp.StageName == 'Closed Won' ) &&
        (Trigger.oldMap.get(opp.Id).StageName!='Closed Won') ) {

        opps.add(opp.Id);

    }

    Map<Id,Opportunity> oppsMap = new Map<Id,Opportunity>( [SELECT Id, Account.Id, CloseDate, OwnerId, Account.Name from Opportunity where Id IN :opps] );

    List <Implementation__c> impToInsert = new List <Implementation__c> ();

    for( Opportunity oppo : oppsMap.values()){
        Implementation__c imp = new Implementation__c ();

        imp.Account__c = oppo.AccountId;
        imp.Name = oppo.Account.Name +' Implementation';
        imp.Phase__c = 'Phase 0';
        imp.Contract_Date__c = oppo.CloseDate;

        impToInsert.add(imp);
    }

try {
        insert impToInsert;
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
    }
}

And here is the test: 

@istest private class CreateImplementation {
testMethod private static void CreateImplementation () {

 Account acco = new Account(Name = 'Acme Test Account', Type = 'Prospect');
    insert acco;

Opportunity opp = new Opportunity(Name = 'Acme Test Opp', CloseDate=System.Today(), AccountId=acco.id, Type= 'New Business', Business_Value__c='NA',Closed_Reasons__c='NA', StageName='Closed Won',Amount=1000);
    insert opp;

 Implementation__c imp = [ SELECT Account__c, Name, Phase__c FROM Implementation__c WHERE Account__c = :acco.id LIMIT 1 ];
 System.assertEquals(imp.Phase__c,'Phase 0');}}

Thanks in advance!
thsrthsr
the trigger is [after update],but there has not  update event in your testclass.so you can add update event to opp for clear the question.
good luck!
Anoop yadavAnoop yadav
Use an update event like the below.

insert opp;
update opp;

Now it will not show you that error.