How can I use the Apex utility class for data manipulation, string parsing, and JSON sterilization?
I am currently developing a Salesforce-based application in which I need to perform various common operations such as data manipulation, string parsing, or JSON sterilization across multiple apex classes. How can I use the Apex utility class to do all this work?
In the context of Salesforce, here is the example given of how you can use the Apex utility class for operations such as data manipulation, string parsing, or JSON sterilization across multiple apex classes:-
Create a utility class
You can start by creating the utility class with static methods for common operations. For instance, let us consider a method for date formatting and JSON serialization:-
Public class MyUtilityClass {
// Method to format a date into a specified format
Public static String formatDate(Date inputDate, String formatString) {
Return inputDate.format(formatString);
}
// Method to serialize an object to JSON format
Public static String serializeToJson(Object obj) {
Return JSON.serialize(obj);
}
}
Using the utility class
Now you can use the utility apex class method in other apex classes throughout your salesforce application:-
@isTest
Public class OpportunityUpdateTriggerTest {
@isTest static void testOpportunityUpdateTrigger() {
// Create test Opportunity record
Opportunity testOpp = new Opportunity(Name=’Test Opportunity’, StageName=’Closed Won’, Amount=1000);
Insert testOpp;
// Verify trigger logic
testOpp = [SELECT Id, Amount FROM Opportunity WHERE Id = :testOpp.Id];
System.assertEquals(1100, testOpp.Amount, ‘Amount should be updated for Closed Won Opportunity’);
// Create JSON data for testing utility class
Map testData = new Map{
‘key1’ => ‘value1’,
‘key2’ => 123,
‘key3’ => true
};
String jsonData = MyUtilityClass.serializeToJson(testData);
System.assertNotEquals(‘’, jsonData, ‘JSON serialization should not be empty’);
}
}