0

I have a apex class on salesforce sandbox account to create records in salesforce .I need to push it to my production account- How can I write a test class without having data dependencies with my production account.

I tried to write a test class on my sandbox- but realized this would not work on my production because the data in the reference objects might be different. For example- in the test class below, the value 333 is the external ID reference of another custom object in my sandbox but my production does not have the same data, so this will fail.

  @isTest(SeeAllData=true) 
    private class TicketRestTestClass {
        static testMethod void validateTicketREST() {
           String ID= RESTTicketController.createticket(55643,3,'9/13/2015 22:30',333,3,3,4,300.0,'sale',2,20.0,null,111);
           Ticket__c b = [SELECT Contact__c,External_TicketID__c,Activity__c,PriceType__c,Date_Time__c,Price__c FROM Ticket__c WHERE Id =:ID];
           System.assertEquals('55643',string.valueOf(b.External_TicketID__c));

        }
    }
3

By default, Apex tests don’t have access to pre-existing data in the org. You should set up test data for your tests. It means you need to first create record of your external Id object inside your test method and then you will pass that id in your rest class createTicket method.

so you need to follow below steps

  1. Set SellAllData=false
  2. Create a record of another object where you will fill your external id value.
  3. Pass external id value after querying inside your test method

    @isTest(SeeAllData=false) 
    private class TicketRestTestClass {
        static testMethod void validateTicketREST() {
           /**************Create another object record*********/
           Another__c another = new Another__c(externalId=333);
           insert another;
           /***************************************************/
           String ID= RESTTicketController.createticket(55643,3,'9/13/2015 22:30',333,3,3,4,300.0,'sale',2,20.0,null,111);
           Ticket__c b = [SELECT Contact__c,External_TicketID__c,Activity__c,PriceType__c,Date_Time__c,Price__c FROM Ticket__c WHERE Id =:ID];
           System.assertEquals('55643',string.valueOf(b.External_TicketID__c));
    
        }
    }
    

You can read Salesforce trailhead Test data module to get started

4
  • Is SeeAllData=false really necessary? isn't that the default behaviour? – mkorman Feb 14 '16 at 20:53
  • It is default behaviour but only if class api version is greater then 28.0 – Himanshu Feb 14 '16 at 23:13
  • And before that? is all the data visible? – mkorman Feb 14 '16 at 23:15
  • Yes that is correct – Himanshu Feb 14 '16 at 23:19

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.