I've noticed that when writing classes, it will often be my first impulse to make certain properties private since they wouldn't need to be referenced by other classes. Take for example a class that generates random strings.
public class RandomStringGenerator{
private final Integer StringLength = 8;
private final list<String> ValidStringCharacters = new list<String>{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a'};
public String getRandomString(){
String ReturnString = '';
for (Integer i = 0; i < StringLength; i++){
Double CharacterToAdd = Math.random() * (ValidStringCharacters.size() - 1);
ReturnString += ValidStringCharacters[(Integer) CharacterToAdd];
}
return ReturnString;
}
}
The two variables StringLength
and ValidStringCharacters
could be made private since all of the other classes could ignore the length of the string and the characters that it is composed of, and just work with what they get. That's fine for all classes that is, except for the test class, which would want to make assertions based on those values to verify that the class is working properly.
@isTest
public class TestRandomStringGenerator{
private static RandomStringGenerator rsg;
static{
rsg = new RandomStringGenerator();
}
public static @isTest void testStringLength(){
system.assert(rsg.getRandomString().length() == rsg.StringLength);
}
public static @isTest void testStringCharacters(){
Set<String> ValidCharacters = new Set<String>(rsg.ValidStringCharacters);
String RandomString = rsg.getRandomString();
for (Integer i = 0; i < RandomString.length(); i++){
system.assert(ValidCharacters.contains(RandomString.substring(i,i+1)));
}
}
}
What is the preferred way to handle this situation? Should those private variables be made public just so that the test class can access them?
testStringLength
andtestStringCharacters
methods in my question don't compile as written since they are referencing the private variables of theRandomStringGenerator
class.