0

I have a method public static List<Case> findCase (Id recordId) that returns List<Case> details. I wrote the following Test and it passed.

List<Case> details  = HighlightComponentController.findCase('5002a000003Y1bYAAS');
System.AssertEquals(0,details.size()); 

This tells me that the method isn't returning the data it should be. When I add this component to a layout in the sandbox it works fine and the data is returned and bound. Please help.

  • 1
    Is this in a unit test, or just an execute anonymous script? – sfdcfox Feb 1 at 0:10
2

Have a look at Understanding Test Data and specifically Isolation of Test Data from Organization Data in Unit Tests:

Starting with Apex code saved using Salesforce API version 24.0 and later, test methods don’t have access by default to pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access data that they create.

You have to create your own test data. A proper unit test setup cannot possibly work with a hard-coded Id. Basic structure of your test should look as follows:

@IsTest
static void testMyMethod()
{
    SObject record = someSetupMethod();
    // your setup method should insert to the database

    Test.startTest();
        List<Case> result = MyClass.myMethod(record.Id);
    Test.stopTest();

    system.assertEquals(new List<Case>(), result, 'Include an informative message here');
}

Please note that even if your test would work with a hard-coded Id in this org, it wouldn't work when you try to deploy elsewhere. Never, ever use hard-coded Ids in your code base.

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.