You need to sign in to do that
Don't have an account?

How do I delete an account with apex and have it delete the child contact records at the same time?
I'm trying to test a trigger that runs on a before delete on an account. When I delete the account in the test I thought that the child contacts would be delete as well but that does not seem to be the case. I don't understand what I'd doing wrong here.
Below is my test method. The last assert fails.
String testuser = UserInfo.getUserID(); //set up the account Account testacct = NewObjFactory.buildTestAcct(0, 'Test Account1', testuser); insert testacct; Account testacct2 = NewObjFactory.buildTestAcct(0, 'Test Account2', testuser); insert testacct2; String accid = testacct.id; // Create the Contacts Contact testcontact = NewObjFactory.buildTestContact(0, testacct.id, testuser, 'Cool', 'Joe'); insert testcontact; String cid = testcontact.id; Contact testcontact2 = NewObjFactory.buildTestContact(0, testacct.id, testuser, 'Cool', 'John'); insert testcontact2; String c2id = testcontact2.id; Contact testcontact3 = NewObjFactory.buildTestContact(0, testacct.id, testuser, 'Cool', 'Paul'); insert testcontact3; //Create the portal records Portal_User_Information__c pu1 = new Portal_User_Information__c(); pu1.user_Name__c = testcontact.id; insert pu1; Portal_User_Information__c pu2 = new Portal_User_Information__c(); pu2.user_Name__c = testcontact2.id; insert pu2; Portal_User_Information__c pu3 = new Portal_User_Information__c(); pu3.user_Name__c = testcontact3.id; insert pu3; String pu3id = pu3.id; //run tests Account ac = [Select ID from account where id = :accid]; Contact c1 = [Select ID from contact where id = :cid]; Test.startTest(); Database.deleteResult result = Database.delete(ac, false); //delete account rec Database.deleteResult result2 = Database.delete(c1, false); Test.stopTest(); // Check data system.debug('start'); System.assert(result.isSuccess()); System.assert(result2.isSuccess()); system.debug('acct del2'); Contact[] c1s = [Select ID from contact where id = :cid]; System.assertEquals(c1s.size(),0);
Below is my test method. The last assert fails.
When you detele account object record then contact will not dleted because there is lookup relation shio not master detail. So you have to delete contact record explicitly.
Please mark this post as a best solution to your problem to help others.