[SalesForce] execute test method via Anonymous Window

I am trying to call my Test class's method to see if I can validate the data that is being created as a part of testSetup. Here is my code:

@isTest
   public class Test_Controller {

    @testSetup static void setUpTestData(){
    Account act = new Account();
    act.Name = 'TestAccount';
    insert act;

    Contact con = new Contact();
    con.AccountId = act.Id;
    con.FirstName = 'FName';
    con.LastName = 'LName';
    insert con;

    List<Case> caseList = new List<Case>();
    for(Integer i=0; i<3; i++){
        Case cs = new Case();
        cs.OwnerId = UserInfo.getUserId();
        cs.AccountId = act.Id;
        cs.ContactId = con.Id;
        cs.Subject ='Test Case'+i;
        cs.Status = 'New';
        cs.Origin = 'Phone';
        caseList.add(cs);
    }

    insert caseList;
    System.debug('caseList' +caseList);
  }

  @isTest
  static void testCases(){
    List<Case> testRecords = [Select Subject From Case];
    System.debug('caseList' +testRecords);
  }
}

When I run this code via Anonymous Window, I am getting this error:

Line: 1, Column: 31
Method is not visible: void Test_Controller.testCases()

Here is how I've tried executing in the Anonymous Window:

Test_Controller.testCases();

Best Answer

As for the error:

Line: 1, Column: 31 Method is not visible: void Test_Controller.testCases()

This is because its declared as private (no access modifier specified is private), and thus you cannot call it outside the context of the class.

From documentation:

If you do not specify an access modifier, the method or variable is private.

To be able to access the method outside the class, you will need to declare it as public, so your method declaration should look as below.

@isTest
public static void testCases(){
   ...
}

UPDATE ON QUESTION

Can I execute test method via Anonymous Window?

No. With a quick test I could confirm that even if you declare it as public, it is not accessible outside the testing framework. Trying it from anonymous window results in error as below:

System.TypeException: Cannot call test methods in non-test context

Notice the below excerpt from this trailhead:

The visibility of a test method doesn’t matter, so declaring a test method as public or private doesn’t make a difference as the testing framework is always able to access test methods. For this reason, the access modifiers are omitted in the syntax.

The available options to be able to run a test method as mentioned in the Run Unit Test Methods are as below:

To run a test, use any of the following:

  • The Salesforce user interface
  • The Force.com IDE
  • The Lightning Platform Developer Console
  • The API
Related Topic