User Story
As a Salesforce developer,
I want an Apex method that checks the length of a string based on a provided maximum character limit (maxChar),
so that strings exceeding the limit are automatically shortened to meet the specified maximum length.
Codes
public class StringUtility {
public static String validateAndShortenString(String inputString, Integer maxChar) {
if (String.isEmpty(inputString)) {
return inputString;
}
return inputString.length() > maxChar ? inputString.substring(0, maxChar) : inputString;
}
}
Test Class
@IsTest
public class StringUtilityTest {
@IsTest
static void testValidateAndShortenString() {
// Test case 1: String length is less than maxChar
String resultLessThan = StringUtility.validateAndShortenString('Short', 10);
System.assertEquals('Short', resultLessThan, 'String shorter than maxChar should remain unchanged.');
// Test case 2: String length is equal to maxChar
String resultEqualTo = StringUtility.validateAndShortenString('ExactSize', 9);
System.assertEquals('ExactSize', resultEqualTo, 'String equal to maxChar should remain unchanged.');
// Test case 3: String length is more than maxChar
String resultMoreThan = StringUtility.validateAndShortenString('TooLongString', 5);
System.assertEquals('TooLo', resultMoreThan, 'String longer than maxChar should be truncated.');
}
}