While working on updating some old custom Apex Salesforce backend tests for our company, I ran into an issue I can't figure out. The code is calling Schema.DescribeFieldResult.getLength()
as described in the documentation but the function does not seem to be returning the correct length. This is causing a large number of tests to fail, as most of them rely on the bit of code to create random data for testing fields. An excerpt from the code is as follows (not a direct excerpt, I don't have access to the code so I'm working from memory at the moment, sorry):
// 'result' is a Schema.DescribeFieldResult passed into the function
Schema.DisplayType dtype = result.getType();
if (dtype == 'String') {
String randomData = getLongRandomString();
Integer maxFieldLength = result.getLength();
return randomData.abbreviate(maxFieldLength);
}
The function returns an abbreviated string as expected, However, the getLength() call here is returning an incorrect value, resulting in test failures because the string is longer than the max field length. For example, there is a custom field called 'Shipping_ZipCode__c' which is configured through the web interface as a text field, with a length of 10 (under the string properties section). For this field, when the tests run I get the following failure:
System.DmlException: Insert failed. First exception on row 0; first error: STRING_TOO_LONG, Reference Number: data value too large: abcdefghijklmnopq.... (max length=10): [Shipping_ZipCode__c]
By my count, the random string it returned is 20 characters long, but I don't know where this value is coming from. My understanding of the documentation, and the answers to other similar questions, .getLength()
should be the way to go (and return 10 for that field).
Is there a different place to fetch the max length from? I'm currently neither terribly familiar with Apex scripting, or the existing code base, so I may be missing something obvious but I am trying to learn. I appreciate any guidance that can be provided!
MyObject__c.Shipping_ZipCode__c.getDescribe().getLength()
returns 20? verify it in anonApex