Why is my After Delete Trigger test class failing?

I have a trigger set up on the Account object for After Delete.
We have an Affiliates table that has a lookup field to Account.

If an Account is merged, I don’t want to delete an Affiliate. It will be updated as usual. If an Account is deleted then I want to delete the Affiliate.

In my trigger I am simply deleting any Affiliates with an empty Account field. That takes care of everything I need.

I manually tested it in the sandbox and it worked as expecting. Keeping the affiliates on a merge and removing on a delete. My Test class is failing and I can’t understand. The Select query is returning a row.

Trigger that runs After Delete for Account:

public class AFFL_AccountDeletion_TDTM extends TDTM_Runnable {


public override DmlWrapper run(List<SObject> listNew, List<SObject> listOld, TDTM_Runnable.Action triggerAction, Schema.DescribeSObjectResult objResult) {

    DmlWrapper dmlWrapper = new DmlWrapper();
    string accMasterRecordID;

    // Only run after delete
    if (triggerAction == TDTM_Runnable.Action.AfterDelete) {


        // Add related affiliations to list to delete
       dmlWrapper.objectsToDelete.addAll((List<SObject>)[SELECT Id FROM Affiliation__c WHERE Account__c =null]);
    }
    return dmlWrapper;
}
}

Test Class:

@isTest (seeAllData = false)
private class AFFL_AccountDeletion_TEST {

@isTest
static void test_delete() {

    Account a1 = [SELECT Id FROM Account WHERE Name = :'test'];
    Affiliation__c affl1 = [SELECT Id FROM Affiliation__c WHERE Account__c = :a1.Id];

    Test.startTest();

    delete a1;

    Test.stopTest();

    System.assert([SELECT Id FROM Affiliation__c WHERE Id = :affl1.Id].isEmpty());
}

@testSetup
static void setup() {

    Account a1 = new Account(Name = 'test');
    insert a1;

    insert new Affiliation__c(Account__c = a1.Id);
 }
}

Answer

TDTM (Table Driven Trigger Management) is driven by custom object records to define the handlers called by a trigger. Since custom objects are data, not metadata, they’re not available in your test context, so the core trigger won’t call your handler.

You can fix this by inserting the appropriate TDTM object in your @testSetup method, or by simply calling your trigger handler directly in the test class and synthesizing the trigger parameters. In this case, since your trigger handler doesn’t use its parameters anyway, we can just pass null and save ourselves some lines of code.

    delete a1;
    new AFFL_AccountDeletion_TDTM().run(null, null, null, null);

Attribution
Source : Link , Question Author : Chancie Pants , Answer Author : David Reed

Leave a Comment