You need to sign in to do that
Don't have an account?
Robert Lange 6
Trying to write test class for trigger that adds Opportunity on Account object
I have written this trigger which adds and opportunity to any new account insertions and account updates (where the account does not have an existing related opportunity). My current test class provides 76% coverage. Any advice would be appreciated!
APEX TRIGGER:
trigger AddRelatedRecord on Account(after insert, after update) {
if (Trigger.isInsert) {
for (Account a : Trigger.new) {
Opportunity opp = new Opportunity();
opp.Name = a.Name + ' Opportunity';
opp.StageName = 'Prospecting';
opp.CloseDate = System.today().addMonths(1);
opp.AccountId = a.Id;
insert opp;
}
}
if (Trigger.isUpdate) {
List<Opportunity> oppList = new List<Opportunity>();
List<Account> accountsWithoutOppsAndGotUpdated = [
SELECT Id, Name
FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Opportunity) AND Id IN :Trigger.new];
for (Account a : accountsWithoutOppsAndGotUpdated) {
oppList.add(new Opportunity(Name = a.Name + ' Opportunity',
StageName = 'Prospecting',
CloseDate = System.today().addMonths(1),
AccountId = a.Id));
}
insert oppList;
}
}
HERE IS MY CURRENT TEST CLASS:
@IsTest
private class AddRelatedRecordTest {
@IsTest public static void addRelatedRecordTestonInsert() {
Account testAcc = new Account(Name = 'My Account Test');
insert testAcc;
update testAcc;
System.assert(true, 'Account Updated');
}
}
APEX TRIGGER:
trigger AddRelatedRecord on Account(after insert, after update) {
if (Trigger.isInsert) {
for (Account a : Trigger.new) {
Opportunity opp = new Opportunity();
opp.Name = a.Name + ' Opportunity';
opp.StageName = 'Prospecting';
opp.CloseDate = System.today().addMonths(1);
opp.AccountId = a.Id;
insert opp;
}
}
if (Trigger.isUpdate) {
List<Opportunity> oppList = new List<Opportunity>();
List<Account> accountsWithoutOppsAndGotUpdated = [
SELECT Id, Name
FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Opportunity) AND Id IN :Trigger.new];
for (Account a : accountsWithoutOppsAndGotUpdated) {
oppList.add(new Opportunity(Name = a.Name + ' Opportunity',
StageName = 'Prospecting',
CloseDate = System.today().addMonths(1),
AccountId = a.Id));
}
insert oppList;
}
}
HERE IS MY CURRENT TEST CLASS:
@IsTest
private class AddRelatedRecordTest {
@IsTest public static void addRelatedRecordTestonInsert() {
Account testAcc = new Account(Name = 'My Account Test');
insert testAcc;
update testAcc;
System.assert(true, 'Account Updated');
}
}
All Answers
I always recommend learning from the official Salesforce Apex Developer Guide Class documents:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_system.htm