Wrote an apex trigger to update associated opportunities when a specific field is updated (which reflects the account's signup stage in our backend).
trigger updateopportunity on Account (after update) {
set<Id> accountIds = new set<Id>();
for (Account acc : Trigger.new)
{
Account old = Trigger.oldMap.get(acc.Id);
if (acc.CD_Status__c=='pending' && acc.CD_Status__c != old.CD_Status__c)
{
accountIds.add(acc.Id);
}
}
if (!accountIds.isEmpty()) {
List <Opportunity> opps = [
select Id, StageName
From Opportunity
where AccountId in: accountIds
and RecordTypeId ='0128d000000pBdUAAU'
and StageName != 'Started SignUp'
];
if (!opps.isEmpty()) {
for (Opportunity opp : opps) {
opp.StageName = 'Started SignUp';
}
update opps;
}
}
}
Read that to deploy in production, I needed to run Apex Class Tests? from the developer console. Not sure how exactly I am meant to format this. the best I could come up wiht, but to no success, was below.
Basically tried creating both an Account and related Opportunity, and then updating said Account's CD_Status__c to 'pending' (the requirement for the trigger), but not entirely sure how to go about initiating the test. I keep getting errors
@isTest
public class updateopportunity {
@isTest static void Testupdateopportunity() {
// set up user
User u1 = [select id from User WHERE email='[email protected]'];
//Run as u1
System.RunAs(u1)
//New Account Record
Account acc = new Account();
acc.Name = 'Test Account';
acc.industry = 'Test';
acc.BillingCountry = 'GB';
acc.Account_Stage__c='Demo Booked';
acc.Website='test.com';
acc.Type='Prospect';
insert acc;
//New Opportunity
Opportunity opp = new Opportunity();
opp.Name = 'Test Opp';
opp.CloseDate = system.today().addDays(7);
opp.StageName = 'Demo Completed';
opp.Type = 'New Business';
opp.RecordTypeId = '0128d000000pBdUAAU';
opp.AccountId = acc.Id;
opp.demobookedby__c='Rod';
opp.datedemobooked__c=system.today();
insert opp;
//Update Account Field
acc.CD_Status__c='pending';
acc.Account_Stage__c='Started SignUp';
updated.acc;
test.stopTest()
//check result of test - but not too sure how to go about this or if this is the correct format at all
Select opp.StageName WHERE opp.AccountId=acc.Id
}
}
opp = [select stagename from opportunity where Id = :opp.id]
then use system.assert to verify the stage has changed.