You are on page 1of 2

Assignment 1

Create a trigger
Before Delete, If Account has at least one Opportunity records associated to it then prevent user from
deleting that Account.
Error message to show: This Account has some related Opportunity record(s), you cannot delete this
Account.

trigger Assignment_1 on Account (before delete) {


//To check if any opportunity is available related to Account before deleting
if(trigger.IsBefore){
if(trigger.IsDelete){
Assignment_1Handler.restrictForDeletion(trigger.old);
}
}
}

//Handler
public class Assignment_1Handler {
public static void restrictForDeletion(List<Account> AccountList){
//taken opportunity who has account
List<Opportunity> oppList=[Select id,AccountId from Opportunity where AccountId In: AccountList];
for(Account acc : AccountList){
//if opportunity size is more than zero then it will show below error
if(opplist.size()>0){
acc.adderror(' Account has some related Opportunity records you cannot delete This Account');
}
}
}

/*
* @Name : Assignment_1Test.apxc
* @Purpose : Apex Assignment 1.
* @Description : Testing by Creating Account With opportunity and try to delete that Account.
* @Since : 13 09 2022
* @date : 13 09 2022
* @OtherRelateFiles : Assignment_1.apxt,Assignment_1Handler.apxc,Assignment_1Test.apxc
*/

@isTest
public class Assignment_1Test {
@testSetup static void setup() {
// Create common test accounts
List<Account> testAccount = new List<Account>();
for(Integer i=0;i<2;i++) {
testAccount.add(new Account(Name = 'TestAccount'+i));
}
insert testAccount;
}

Assignment 1 1
@isTest static void TestDeleteAccountWITHOUTOpportunity() {
// Test data setup
// Create an account without an opportunity, and try to delete it
Account accountRecord = [SELECT Id,Name FROM Account WHERE Name='TestAccount0' LIMIT 1];
}

@isTest static void TestDeleteAccountWITHONEOpportunity() {


// Test data setup
// Create an account with an opportunity, and then try to delete it
Account accountList = [SELECT Id,Name FROM Account WHERE Name='TestAccount1' LIMIT 1];
Opportunity TestOpportunity = new Opportunity(Name=accountList.Name + ' Opportunity',
StageName='Prospecting',
CloseDate=System.today().addMonths(1),
AccountId=accountList.Id);
insert TestOpportunity;
// Perform test
Test.startTest();
Database.DeleteResult result = Database.delete(accountList, false);
Test.stopTest();
// Verify
// In this case the deletion should have been stopped by the trigger,
// so verify that we got back an error.
System.assert(!result.isSuccess());
System.assert(result.getErrors().size() > 0);
}
}

Code Coverage 100%


TestDeleteAccountWITHONEOpportunity() = 100% of Assignment_1Handler || 100% of Assignment_1
TestDeleteAccountWITHOUTOpportunity() = 20% of Assignment_1Handler || 0% of Assignment_1

Assignment 1 2

You might also like