1

I don't know much about Salesforce, but I've learned a lot these last few months. I was given the assignment to create an app for the Salesforce App Exchange, so that our API would be available inside of Salesforce.

When I first created the app, I put our API key inside of an Apex class. When I submitted the app for security review, this was rejected. I asked for advice on salesforce.stackexchange.com and I was told that sensitive data such as API keys should go into a Protected Custom Setting. Which I did.

So I ended up with code like this:

    Http httpProtocol = new Http();
    HttpRequest request = new HttpRequest();
HttpResponse response;

// we need a string that looks like this: 
// /[email protected]&pass=test1234
String authpoint = 'authtoken?service=salesforce&user=' + ps.SameDayUsername__c  + '&pass=' + ps.SameDayPassword__c;
    String endpoint = be + authpoint;

    request.setEndPoint(endpoint);
    request.setMethod('GET');
    request.setHeader('Accept', 'application/json');
    request.setHeader('x-api-key', PrivateIncInfo__SameDayConfiguration__c.getOrgDefaults().PrivateIncInfo__xApiKey__c);

try {
    // Send the HTTP request and get the response.
    // response.getBody() returns the JSON as a String.

        if (Test.isRunningTest() && (mock!=null)) {
            response = mock.respond(request);
        } else {
            response =  httpProtocol.send(request);
        }

This seemed to work, but now when I run the unit test, it is now failing on this line:

    request.setHeader('x-api-key', PrivateIncInfo__SameDayConfiguration__c.getOrgDefaults().PrivateIncInfo__xApiKey__c);

I get this error:

System.NullPointerException: Argument 2 cannot be null

So what is the normal way of dealing with this? How do I call this code and have it work in a test?

1 Answer 1

3

You have to create the records. See also (emphasis mine):

Isolation of Test Data from Organization Data in Unit Tests

Starting with Apex code saved using Salesforce API version 24.0 and later, test methods don’t have access by default to pre-existing data in the organization, such as standard objects, custom objects, and custom settings data, and can only access data that they create. However, objects that are used to manage your organization or metadata objects can still be accessed in your tests such as:

  • User
  • Profile
  • Organization
  • AsyncApexJob
  • CronTrigger
  • RecordType
  • ApexClass
  • ApexTrigger
  • ApexComponent
  • ApexPage

You can create an org default setting in a variety of ways. One such:

MySetting__c defaults = MySetting__c.getOrgDefaults();
defaults.SomeField__c = 'Some Value';
upsert defaults;

You must log in to answer this question.

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