+ Start a Discussion
jonathanbernddf20131.387825590468351E12jonathanbernddf20131.387825590468351E12 

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY - Test class

Hi
Having some trouble. Wrote a trigger/class to post info from a new case to the lead object. I cannot get a test class to insert a case.

The above is the error message with 'radioCaseToLead: execution of AfterInsert'

The line of code to referred to as a problem is 'insert newleads;'

Any insight would be great.
Best Answer chosen by jonathanbernddf20131.387825590468351E12
pconpcon
The reason it's not working is that you do not have any campaigns created in your test.  You will need to create all the test data prior to running your test.  Doing something like this should get you where you need.

@isTest
public class TestRadioCaseLead {
    static testmethod void caseCreate() {
        Campaign testCampaign = new Campaign(
            Name = '_unittest_campaign_: 001',
            Type = 'Radio',
            Status = 'In Progress',
            StartDate = Date.now().addDays(-1)
        );

        insert testCampaign;

        Case caseToCreate = new Case(
            Product__c = 'TEST',
            Type = 'Trigger',
            Status = 'New',
            Origin = 'Radio',
            RecordTypeId = '012o00000005ylh',
            How_did_you_hear__c = 'Radio',
            Subject = 'Test Trigger',
            Description = 'And make sure it works',
            FirstName__c = 'Test',
            LastName__c = 'Trigger',
            Email__c = 'testtrigger@testtrigger.com',
            Phone__c = '0000000000'
        );

        Test.startTest();

        insert caseToCreate;

        Test.stopTest();

        List<Lead> results = [
            select FirstName,
                LastName,
                Email,
                Phone,
                Company,
                Status,
                LeadSource,
                ProductInterest__c,
                Description
            from Lead
        ];

        System.assertEquals(1, results.size(), 'Did not get the expected number of leads back');
        // Add more asserts
    }
}


All Answers

pconpcon
Can you please add the code you have written for your test class?  Please use the "add a code sample" button when doing this.
Bhawani SharmaBhawani Sharma
Please share code you have written so far.
Deepak Kumar ShyoranDeepak Kumar Shyoran
Try to run your test class by "Disable Parallel Apex Testing"  under Setup > Develop > Apex Test Execution > Option > and then selecting the checkbox for Disable Parallel Apex Testing. May be it helps your problem.
jonathanbernddf20131.387825590468351E12jonathanbernddf20131.387825590468351E12
Thanks for the quick responses everyone. I was away, but back now. Here's the code so far:
Class then triggers.
public with sharing class RadioCaseToLeadToCampaign {
 
      //Initialize Static Variable
      public static Boolean firstcall=True;

      //Set class
      public static void radioCaseToLead (list<Case> newcase) {

      if(!firstcall) {
          System.debug('Exiting radioCaseToLead because of !firstcall');
          return;
          }   
         
 
       //Make list for leads
       list<Lead> newleads = new list<Lead>();   
    
       for(Case cs : newcase) {
            Lead ncl = new Lead();
            ncl.FirstName = cs.FirstName__c;
            ncl.LastName = cs.LastName__c;
            ncl.Email = cs.Email__c;
            ncl.Phone = cs.Phone__c;
            ncl.Company = 'Radio Case';
            ncl.Status = 'Open - Not Contacted';
            ncl.LeadSource = cs.Origin;
            ncl.ProductInterest__c = cs.Product__c;
            ncl.Description = cs.Source__c + ': ' + cs.Subject + ' - ' + cs.Description;
            newleads.add(ncl);
        } 
    insert newleads;
    }
    //now find campaign radio whatever and then assign campaign members. 
    
     //Set class
      public static void radioLeadToCampaign (list<Lead> newleads) {

          if(!firstcall) {
            System.debug('Exiting radioLeadToCampaign because of !firstcall');
             return;
            } else {
            firstcall=false;
           }
    
        //Get most recent radio campaign even if it is completed assuming that the Inquiry heard from the latest radio campaign.
        list<Campaign> radioCamp = [SELECT Id, Name,IsActive, Type, StartDate, Status FROM Campaign 
        WHERE Type = 'Radio' AND Status <> 'Aborted' AND Status <> 'Planned' ORDER BY StartDate DESC LIMIT 1];
   
   
        //Make list for Campaign Members
        list<CampaignMember> cmembs = new list<CampaignMember>();
        
        //Get relevant leads
        for (Lead l :newleads){
            if(l.LeadSource =='Radio'){
        
               CampaignMember ncm = new CampaignMember();
               ncm.CampaignId = radioCamp[0].Id;
               ncm.LeadId = l.Id;
               ncm.LeadSource__c = l.LeadSource;
               ncm.Status = 'Responded';
               cmembs.add(ncm);
            } 
          }
    
      insert cmembs;    
      
     }
}
trigger radioCaseToLead on Case (after insert) {
    
        for (Case cs :Trigger.new) {
            if(cs.Record_Type_Name_as_String__c =='Inquiry' && cs.Origin== 'Radio') {
            RadioCaseToLeadToCampaign.radioCaseToLead(Trigger.new);
            }
        }
}
trigger radioLeadToCampaign on Lead (after insert) {
    
        RadioCaseToLeadToCampaign.radioLeadToCampaign(Trigger.new);
        
}





pconpcon
What about the test that is causing you to get the error?
jonathanbernddf20131.387825590468351E12jonathanbernddf20131.387825590468351E12
Sorry for the late response. 
Apex Test Result Detail

Time Started 9/5/2014 6:30 PM
Class TestRadioCaseToLead
Method Name makeCaseForLead
Pass/Fail Fail
Error Message System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, radioCaseToLead: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, radioLeadToCampaign: execution of AfterInsert

caused by: System.ListException: List index out of bounds: 0

Class.RadioCaseToLeadToCampaign.radioLeadToCampaign: line 58, column 1
Trigger.radioLeadToCampaign: line 3, column 1: []

Class.RadioCaseToLeadToCampaign.radioCaseToLead: line 31, column 1
Trigger.radioCaseToLead: line 5, column 1: []
Stack Trace Class.TestRadioCaseToLead.makeCaseForLead: line 7, column 1
pconpcon
This is failing because the following line is returning no results (Line 46-47 of code above)
list<Campaign> radioCamp = [SELECT Id, Name,IsActive, Type, StartDate, Status FROM Campaign WHERE Type = 'Radio' AND Status <> 'Aborted' AND Status <> 'Planned' ORDER BY StartDate DESC LIMIT 1];
The error happens on Line 58
ncm.CampaignId = radioCamp[0].Id;
this could be occuring because you do not have the correct test data setup inside your TestRadioCaseToLead class (would need to include that code for further analysis).  Regardless of that, I would modify your code to either do an addError ir radioCamp.isEmpty or just retrun if it is empty to avoid this error

List<Campaign> radioCamp = [
     select Name,IsActive,
          Type,
          StartDate,
          Status
     from Campaign
     where Type = 'Radio' and
          Status <> 'Aborted' and
          Status <> 'Planned'
     order by StartDate desc
     limit 1
];

if (radioCamp.isEmpty()) {
     newLeads.get(0).addError('Unable to find campaign');
}

OR

if (radioCamp.isEmpty()) {
     return;
}

If this code works doing manual testing then it may be how your test data is setup.  Please include that class as well for further analysis.
jonathanbernddf20131.387825590468351E12jonathanbernddf20131.387825590468351E12
Thanks so much, let me try that and if I'm still having trouble, I'll get back to you.

jonathanbernddf20131.387825590468351E12jonathanbernddf20131.387825590468351E12
Hmm - OK - so here's a very siimple insert that's not working. I've put in your 'error' code in the class.
@isTest
public class TestRadioCaseLead {
    //Returns a valid mock Case
    
    static testmethod void caseCreate() {
    

    Case caseToCreate = new Case();
    
    caseToCreate.Product__c = 'TEST';
    caseToCreate.Type = 'Trigger';
    caseToCreate.Status = 'New';
    caseToCreate.Origin='Radio';
    caseToCreate.RecordTypeId='012o00000005ylh';
    caseToCreate.How_did_you_hear__c = 'Radio';
    caseToCreate.Subject = 'Test Trigger';
    caseToCreate.Description='And make sure it works';
    caseToCreate.FirstName__c = 'Test';
    caseToCreate.LastName__c = 'Trigger';
    caseToCreate.Email__c = 'testtrigger@testtrigger.com';
    caseToCreate.Phone__c = '0000000000';
    insert caseToCreate;
    }
}

pconpcon
The reason it's not working is that you do not have any campaigns created in your test.  You will need to create all the test data prior to running your test.  Doing something like this should get you where you need.

@isTest
public class TestRadioCaseLead {
    static testmethod void caseCreate() {
        Campaign testCampaign = new Campaign(
            Name = '_unittest_campaign_: 001',
            Type = 'Radio',
            Status = 'In Progress',
            StartDate = Date.now().addDays(-1)
        );

        insert testCampaign;

        Case caseToCreate = new Case(
            Product__c = 'TEST',
            Type = 'Trigger',
            Status = 'New',
            Origin = 'Radio',
            RecordTypeId = '012o00000005ylh',
            How_did_you_hear__c = 'Radio',
            Subject = 'Test Trigger',
            Description = 'And make sure it works',
            FirstName__c = 'Test',
            LastName__c = 'Trigger',
            Email__c = 'testtrigger@testtrigger.com',
            Phone__c = '0000000000'
        );

        Test.startTest();

        insert caseToCreate;

        Test.stopTest();

        List<Lead> results = [
            select FirstName,
                LastName,
                Email,
                Phone,
                Company,
                Status,
                LeadSource,
                ProductInterest__c,
                Description
            from Lead
        ];

        System.assertEquals(1, results.size(), 'Did not get the expected number of leads back');
        // Add more asserts
    }
}


This was selected as the best answer
jonathanbernddf20131.387825590468351E12jonathanbernddf20131.387825590468351E12
You da man - thanks:)  BTW - is there a best practice in creating a test record between my CaseToCreate with all the variables etc. and yours, just putting them in within the ();?

Thanks again
pconpcon
The best practices really is to create the data in a TestUtils type method and to do all of your setup outside of the Test.startTest() and Test.stopTest() when you call the startTest, your limits are reset and thus your test because a true test of the DML limits.  Otherwise your limits would include your setup.  For more of a break down on testing you can see a presentation I gave on "Testing for Humans" [1] and a blog post [2] I wrote about writing your first trigger.  The testing portion of that post may be of some use to you.

[1] http://pcon.github.io/presentations/testing/
[2] http://blog.deadlypenguin.com/blog/2014/07/23/intro-to-apex-auto-converting-leads-in-a-trigger/
jonathanbernddf20131.387825590468351E12jonathanbernddf20131.387825590468351E12
Just a quick follow up. Would you mind helping me with my test factory by telling me where I am wrong? I started with a testFactory - 
@isTest public class TestFactory {
    /*Returns a valid mock Case
    *i: and integer to make each Case unique.
    */
    public static Case buildTestCase(Integer i) {
    
    Case caseToCreate = new Case();
    
    caseToCreate.Product__c = 'TEST'+ i;
    caseToCreate.Type = 'Trigger';
    caseToCreate.Status = 'New';
    caseToCreate.Origin='Radio';
    caseToCreate.RecordTypeId='012o00000005ylh';
    caseToCreate.How_did_you_hear__c = 'Radio';
    caseToCreate.Subject = 'Test Trigger';
    caseToCreate.Description='And make sure it works';
    caseToCreate.FirstName__c = 'Test';
    caseToCreate.LastName__c = 'Trigger' + i;
    caseToCreate.Email__c = 'testtrigger@testtrigger.com';
    caseToCreate.Phone__c = '0000000000';
    return caseToCreate;
    }
    
    /*Returns a valid mock Lead
    *i: and integer to make each Lead unique.
 
    public static Lead buildTestLead(Integer i) {
    
    Lead leadToCreate = new Lead();
    
    leadToCreate.FirstName = 'Test'+ i;
    leadToCreate.LastName = 'Trigger';
    leadToCreate.Status = 'Open - Not Contacted';
    leadToCreate.Phone='1234567890';
    leadToCreate.Email='asdf@asdf.com';
    leadToCreate.Description = 'This comes from Case';
    return leadToCreate;
    }
       */
       
    /*Returns a valid mock Campaign
    *i: and integer to make each Campaign unique.
   
    public static Campaign buildTestCampaign(Integer i) {
    
    Campaign campaignToCreate = new Campaign();
    
    campaignToCreate.Name = 'Test'+ i;
    campaignToCreate.Status = 'Open - Not Contacted';
    campaignToCreate.IsActive=true;
    return campaignToCreate;
    }
    */
    
    
    /*Returns a valid mock CampaignMember
    *i: and integer to make each CampaignMember unique.
    
    public static CampaignMember buildTestCampaignMember(Integer i) {
    
    CampaignMember cmToCreate = new CampaignMember();

    return cmToCreate;
    }
    */
}