+ Start a Discussion
Andrew Hoban 6Andrew Hoban 6 

System.LimitException: Too many query rows: 50001 on Test Class

Hi all, i am trying to put a test class for a controller  into a production org, however I am getting the error message:

System.LimitException: Too many query rows: 50001 Class.MascotController.getContacts: line 12, column 1 Class.MascotController.<init>: line 7, column 1 Class.MascotControllerTestClass.MascotController: line 14, column 1

Is there something I need to add to the code in order for this to work?

public class MascotController 
   public List<Contact> contacts{get;set;}

   public MascotController()

   public void getContacts()
        Integer count = [SELECT COUNT() FROM Contact];
        Integer rand = Math.floor(Math.random() * count).intValue();
        Set<Id> contactIds = new Set<Id>();
        contacts = new List<Contact>();

        for(CampaignMember cm : [Select Id, ContactId from CampaignMember where Status = 'Sent' and Campaign.Name = '2014/15 Mascot Data'])
        List<String> orderBys = new List<String>{'Email Asc','Email Desc','Lastname Asc','Firstname Desc','LastModifiedDate Desc','LastModifiedDate Asc','CreatedDate Asc','CreatedDate Desc','Id Asc','Id Desc'};

        String orderBy = orderBys.get(Math.mod(rand,orderBys.size()));

        contacts = Database.query('Select Name From Contact where ID in :contactIds Order By ' + orderBy + ' Limit 2 OFFSET :rand');

Test Class:
private class MascotControllerTestClass {
     static testMethod void MascotController() {
        Account ac = new Account(name ='Daniel') ;
        insert ac; 
        Contact con = new Contact(LastName ='testCon',AccountId = ac.Id);
        insert con;  
        Campaign camp = new Campaign (Name = '2014/15 Mascot Data');

        insert camp;
        CampaignMember  capMember = new CampaignMember(Status ='To be Called', contactid=con.id, CampaignId = camp.id);
        insert capMember;
        PageReference pageref = Page.mascotPage;
        MascotController cont = new MascotController();

Fabien TaillonFabien Taillon
You should remove (SeeAllData=true) at the top of your test class, and create all your test data you need in your test method (seems you're already doing it). Otherwise, your test will be dependend of existing data in your org. That's why your test class is working on your Sandbox and not in your Production environment.
Also, you should use Test.startTest() and Test.stopTest() (around MascotController cont = new MascotController();) to avoid your data creation to count in your test governor limits.
You can see more about Test classes here :
https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods (https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods" target="_blank)