When should I use the Testvisible Annotation?
I understand that @TestVisible is used to allow Unit Tests access to private and protected methods.
What I was wondering is, when is it appropriate to use this annotation?
For example, I have a list generated in a wrapper class that allows selection and processing of Users as below:
public class uUser {
public User user {
get;
set;
}
public Boolean selected {
get;
set;
}
public uUser(User u) {
user = u;
selected = false;
}
}
I then used the following Apex to select all or deselect all these Users:
private Boolean isAllUsersSelected {
get {
if (isAllUsersSelected == null) {
isAllUsersSelected = false;
}
return isAllUsersSelected;
}
set;
}
public PageReference selectAllUsers() {
if (isAllUsersSelected == false) {
isAllUsersSelected = true;
for (uUser user : userList) {
user.selected = true;
}
}
else {
isAllUsersSelected = false;
for (uUser user : userList) {
user.selected = false;
}
}
return null;
}
Because this depends a lot on whether the isAllUsersSelected variable is true or false, I wondered whether or not it is a good idea and appropriate to use a @TestVisible method, given its access modifier is private?
I use a lot of custom messaging assigned to final strings and they have an access of private
@TestVisible private static final string REQERROR = 'There was an error processing your request'; Adding the @TestVisible annotation allows me to use this property in my test classes to assert the appropriate messages are displayed while allowing me to change the message and not break the test classes.
The alternative would be to make the access public but I like to only make things public when they need to be public.
You can find use cases for this in many places. The one thing I would says is if you have a method that is private you should generally not need to use @TestVisible because the method itself is private and thus if a test does not cover it without the @TestVisible then either there is something wrong with your code, test, or the method is unused. The exception to the above is a helper method that you make private. If you want to use the results of that method in your assertions then you would need to use the @TestVisible