How to resolve error non static method cannot be referenced from a static context?

40.4K    Asked by bruce_8968 in Salesforce , Asked on Aug 17, 2021

Here is the Test class:

@isTest private with sharing class Genereratortest { @TestSetup static void createPayloadtest() { List<_Site__c> studySites = new List<_Study_Site__c>{ TestDataFactory.createStudySite('test','Data'), }; Test.startTest(); SSUDataJSONGenerator.createPayload(studySites,'INSERT'); Test.stopTest(); }
} }

When I run this test class I am getting below error

The nonstatic method cannot be referenced from a static context: String SSUDataJSONGenerator.createPayload(List, String)

Not sure what’s going wrong with the test class, please suggest a possible solution.


Answered by Ono Imai

There is one simple way of solving the non-static variable cannot be referenced from a static context error. Address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.


As written, you've made it so you have to construct an instance of your class:

        Test.startTest();
        SSUDataJSONGenerator generator = new SSUDataJSONGenerator();
        generator.createPayload(studySites,'INSERT');
        Test.stopTest();

If you didn't mean to add this complexity, change your method to static:

public static String createPayload(List sobjrecords, String operation) {
You also need to use @isTest to denote a unit test method. @testSetup is only for creating test data (if necessary).
@isTest
 class SSUDataJSONGeneratorTest {
 @isTest
 static void createPayloadtest() {
           List studySites = new List{
            TestDataFactory.createStudySite('test','Data'),
        };
        Test.startTest();
        SSUDataJSONGenerator.createPayload(studySites,'INSERT');
        Test.stopTest();
    }
}

Your Answer

Answer (1)

To resolve the error "Non-Static Method Cannot Be Referenced From a Static Context," you can do one of the following:


Make the Method Static: If the method does not rely on instance-specific data, you can declare it as static. This allows it to be called from a static context.

public static void myMethod() {
    // Method implementation
}

Create an Instance of the Class: If the method is non-static and belongs to a class, you need to create an instance of the class to access the method.

Copy code
MyClass obj = new MyClass();
obj.myMethod(); // Call the non-static method using the object

Convert the Calling Method to Non-Static: If the method calling the non-static method is static, consider making it non-static or creating an instance of the class containing the non-static method.

By applying one of these approaches, you can resolve the error and ensure that the non-static method can be referenced correctly.


8 Months

Interviews

Parent Categories