I'm new to Apex coding and have created a trigger that closes an Opportunity (StageName='Closed') whenever a checkbox in the related contract is checked (ApStatus=true). After searching around I came up with the following code and associated test that passed 100% coverage on the Sandbox. However, when I try to deploy to production, it fails with the following error code:
System.QueryException: List has no rows for assignment to SObject Stack Trace: Class.testContract2Opp.testUpdate: line 27, column 1
How can the test runs work on Sandbox and then generate errors on deployment? Any help is much appreciated!
The trigger:
trigger Contract2Opp_Close on Contract (after update) {
Set<Id> oppIds = new Set<Id>();
for(Contract c:Trigger.new) {
if(c.ApStatus__c==true && Trigger.oldMap.get(c.id).ApStatus__c!=true) {
oppIds.add(c.Opportunity_related_to__c);
}
}
for(Opportunity[] oppList:[select id from opportunity where id in :oppIds]) {
for(Opportunity opp:oppList) {
opp.StageName = 'Closed';
opp.Closed_Approved__c = true;
}
update oppList;
}
}
And it's test class:
@isTest
public class testContract2Opp {
static testMethod void testUpdate(){
Account acct = new Account (Name = 'Acme, Inc.');
insert acct;
Opportunity testOpp = new Opportunity(
Name = 'Test Opportunity',
StageName='Qualified',
CloseDate=System.today(),
AccountId = acct.Id,
Input_device__c='ebook',
Biz_Type__c='NB');
insert testOpp;
Contract testcontract = new Contract(
Name='Test Contract',
Opportunity_related_to__c = testOpp.Id,
StartDate=System.today(),
ContractTerm=4,
Status = 'Draft',
ApStatus__c=false,
Short_Company_Name__c = 'TOTO',
AccountId = acct.Id);
insert testcontract;
testcontract.ApStatus__c=true;
update testcontract;
testOpp = [SELECT Name, StageName
FROM Opportunity
WHERE StageName = :'Closed'];
System.assertEquals('Closed', testOpp.StageName);
}
}