Follow up to Spring ’16 Feature – Run Script for Sandbox

A follow-up post to http://philthecloud.com/spring-16-feature-run-scripts-for-sandbox/ and the Spring ’16 release feature Run Script after Sandbox Create or Refresh.

This was the original use case I wanted to cover (pending a support case and bug issues), functionality to auto refresh a custom setting with environment information.

In a production environment I have a custom setting (hierarchy type) that contains the environment Id, Name, Type, and URL.

envrionmentsettings

…and it has the following data:

es_data

When a sandbox is created or refreshed from the production environment it pulls the custom setting data with it, but in this use case, it no longer relevant for the environment. I’m coming from the production environment, but I now want the relevant Sandbox environment information.  Now with an apex class that implements SandboxPostCopy interface, I can have this data auto populated when the sandbox is created or refreshed.  Here’s what the apex class looks like:


global class sandboxCreateRefreshScript implements SandboxPostCopy
{

global void runApexClass(SandboxContext context)
{

Environment_Settings__c es = Environment_Settings__c.getorgdefaults();

es.Environment_Type__c = 'Sandbox';
es.Environment_URL__c = URL.getSalesforceBaseUrl().toexternalform();
es.Environment_Id__c = String.valueof(context.sandboxId());
es.Environment_Name__c = context.sandboxName();
update es;

}
}

and test class…..


@isTest
private class sandboxCreateRefreshScriptTest
{
@testSetup static void testData()
{
Environment_Settings__c es = new Environment_Settings__c();
es.Name = 'test';
insert es;
}
@isTest static void testSandboxPostCopyScript()
{

test.startTest();
sandboxCreateRefreshScript sandboxScriptclass = new sandboxCreateRefreshScript();
Test.testSandboxPostCopyScript(sandboxScriptclass, UserInfo.getOrganizationId(), UserInfo.getOrganizationId(), 'sandboxName');
test.stoptest();

Environment_Settings__c es2 = Environment_Settings__c.getorgdefaults();
system.assertNotEquals(null, es2.Environment_Id__c);
system.assertEquals('Sandbox',es2.Environment_type__c);
system.assertEquals('sandboxName',es2.Environment_Name__c);
}
}

On the sandbox wizard you’ll see we have the option of specifying the apex class to run that has the SandboxPostCopy interface.  Simply input the class name and submit.

testscriptselection

 

After the sandbox refreshes, we now have our data auto populated:

Screen Shot 2016-04-25 at 12.05.34 PM