I am writing a test class on trigger which deletes a record if cancelled checkbox is selected on record detail page.

In my test class, I am trying to set the cancel checkbox to true and delete the record but getting error: "Missing id at index: 0" for the line delete erc;

@istest private class cancelEvent_test {
    testMethod private static void testCancelERC(){

        //insert Event
        event__c testEvent = TestData.nEvent(1);
        insert testEvent;

        //insert contact
        contact testContact = TestData.nContact(1);
        insert testContact;

        //assign newly created event and contact to ERC
        Event_Registered_Contact__c ERC = new Event_Registered_Contact__c(event__c = testEvent.id, Contact__c = testContact.id);
        ERC.Cancel__c = true;
        delete erc;
            delete erc;
        } catch (system.DMLException e) {

TestData Class:

@istest public class TestData{        
    //Create a new Contact
    public static contact nContact(integer i){
        contact nContact = new contact();
        nContact.FirstName = 'contact'+i;
        nContact.LastName = 'name'+i;
        nContact.Email = 'contact'+i+'@gmail.com';
        return nContact;

    //Create a new Event
    public static Event__c nEvent(integer i){
        Event__c nEvent = new Event__c();
        nEvent.name = 'Test_Event'+i;
        return nEvent;

Also, I just began writing test classes after learning from internet, Can you please look into the code and suggest me any improvements

  • if you can share your Apex class then it would be easy for us to understand that what exactly are you trying to do. – Abbas May 5 '15 at 18:32
  • 3
    You first need to insert ERC before you can delete it. – crmprogdev May 5 '15 at 18:41

You need to insert a record before you can delete it, as mentioned in the comments. You also have a flaw in your test, because it looks like you are hoping the delete fails, but if it doesn't your test will pass. A better pattern would be more like the following:

DmlException expectedException;
    delete erc;
catch (DmlException dmx)
    expectedException = dmx;

system.assertNotEquals(null, expectedException);

This way if there is no DmlException, the test will fail.

  • Actually, I am expecting delete to pass – sf_user May 5 '15 at 19:51
  • Then you would change it to unexpectedException and assertEquals. – Adrian Larson May 5 '15 at 19:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.