function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Long TruongLong Truong 

Only top-level class methods can be declared static

I copy and paste this sample code from Salesforce into the execute anonymous, but I get this error:

Line: 4, Column: 34
Only top-level class methods can be declared static

Why would a sample code from Salesforce not work? Thanks!

@isTest
                    
private class TestRunAs {
   public static testMethod void testRunAs() {
      // Setup test data
      // This code runs as the system user
      Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
      User u = new User(Alias = 'standt', Email='standarduser@testorg.com', 
      EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName='standarduser@testorg.com');

      System.runAs(u) {
         // The following code runs as user 'u' 
         System.debug('Current User: ' + UserInfo.getUserName());
         System.debug('Current Profile: ' + UserInfo.getProfileId()); 
      }
   }
}

 
Best Answer chosen by Long Truong
Himanshu ParasharHimanshu Parashar
Hi Long,

It is because this is a test class which can't be executed from the execute anonymous section. in order to execute save it as a new class in Apex Class section and they Click on Run Test.

Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

All Answers

Rahul BorgaonkarRahul Borgaonkar
Hi,

Note the following about the content of an anonymous block (for executeAnonymous, the code String):
• User-defined methods cannot include the keyword static.

Regards
Himanshu ParasharHimanshu Parashar
Hi Long,

It is because this is a test class which can't be executed from the execute anonymous section. in order to execute save it as a new class in Apex Class section and they Click on Run Test.

Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
This was selected as the best answer
Yeliz Taşkıran 9Yeliz Taşkıran 9
User-added image
Venkatramana Kapavari 10Venkatramana Kapavari 10
It is because this is a test class which can't be executed from the execute anonymous section. in order to execute save it as a new class in Apex Class section and they Click on Run Test.