1

I am testing some HTTP callouts in Apex and instead of passing a newly created MyHttpCalloutMockImpl object in the test method every time, thought of declaring the same at class level and reusing it in each test method that tests a callout.

But this fails to compile stating "Variable does not exist". What is the reason for this? Here goes my code:

@isTest(seeAllData = false)

public class MyControllerTest {

HttpCalloutMockImpl mockImpl = new HttpCalloutMockImpl();

@testSetup static void setup() {
    //insert some setup data

}

public static testMethod void testMyMethod1() {
    Test.startTest();
    MyController ctrlObj = new MyController();
    Test.setMock(HttpCalloutMock.class, mockImpl);
    ctrlObj.sync1();
    Test.stopTest();
}

public static testMethod void testMyMethod2() {
    Test.startTest();
    MyController ctrlObj = new MyController();
    Test.setMock(HttpCalloutMock.class, mockImpl);
    ctrlObj.sync2();
    Test.stopTest();
}
}
1
  • static. Everything is static except for your mockimpl. Make it static and that will work
    – kurunve
    Commented Jan 30, 2018 at 14:57

2 Answers 2

3

You cannot see instance variables in static methods (though the converse is not true). As stated in the comments, add the static keyword:

static MyMock mock = new MyMock();
3

Each test method in a test class is executed in a separate transaction. Although you'd be able to "see" a static variable in each test method in the sense that it would be defined, it'd always be null (unless you write a static initializer, which case you'd just get a new instance) because static variables are reset at transaction boundaries. You can't store and reuse data from one test method to another.

1
  • Maybe this should be a new question rather than a comment on a 5-yo answer, but: if a TestSetup method sets the value of of a class-level static variable, would the value persist from each run of the setup to the test method? Commented Jan 9, 2023 at 18:36

You must log in to answer this question.

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