I have the following setup method:

@testSetup static void settingUp(){
  Case exampleCase = new Case(Status='Imminent');
  insert exampleCase;

static testMethod void testStatus(){
  Case c = [SELECT Id, Status FROM Case WHERE Id = :exampleCase.Id];

I have tried this however I get the following error:

Variable does not exist: exampleCase.Id

How can I refer to the original case I inserted? Thanks!

1 Answer 1


You need to requery the records that you created in @testSetup as if they existed outside the scope of your method, as the variable exampleCase doesn't exist in your method testStatus. @testSetup simply creates the record in the context of the test transaction - it does not "automatically" contain them in memory in the ensuing test methods.

This would return the record you created:

Case c = [SELECT Id, Status FROM Case];

as would this:

Case c = [SELECT Id, Status FROM Case WHERE Status = 'Imminent'];
  • Thanks, Brian. The problem is, in my test class, I'm inserting several cases in the testSetup, so I really need the specific Id for "exampleCase"
    – fred
    Dec 23, 2015 at 15:01
  • 4
    With using @testSetup , it might be a good idea to statically declare a set of names (outside of the @testSetup method) to assign to the objects being created. You can then use those (in lieu of having the Ids) to find specific records in the case where you're creating more than one record of a given sObject.
    – Derek F
    Dec 23, 2015 at 15:03
  • 2
    @DerekF's idea is a good one; an alternative is to insert the mocked objects as a list with predefined names that sort - for example 00MyName, 01MyName, ... and then when you fetch in the testmethod using an order by, you can refer to the record you are interested in by index [0], or [1]
    – cropredy
    Dec 23, 2015 at 18:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .