4

How can I test private methods in an apex controller ? For instance this example:

 private static string getUserId(String str){
            string UserId = '';
            if(ref != null){
                String[] str = ref.split('bshc=', 2);
                system.debug('***********str***************'+ str[1]);
                String commUserLastdigit = str[1].substring(0,11);
                system.debug('***********communityUserId ***************'+ commUserLastdigit );
                CommUserId = '005c' + commUserLastdigit ;
            }
        return UserId ;
        }
13

Use the TestVisible annotation.

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_annotation_testvisible.htm

@TestVisible 
private static void yourMethod() {
4
  • Damn. Never knew that. Very handy. Jul 30 '14 at 7:28
  • Private methods are just an implementation detail and should not have explicit tests for them. Test behavior of public API (stackoverflow.com/a/105021/2047418). Feb 13 '17 at 15:54
  • Thanks for your comment @FilipBartuzi . In fact I disagree with that opinion ;) Of course it is good practice not to test private methods (in most cases) but at the same time there are reasons to do that. Everything should be driven by common sense. In case of testing private methods I align with Dave Sherohman opinion. Personaly I think that delegating logic (specyfic just for one class) from private methods to external public classes is kinda silly - you not only expose logic that should not be accessible externally, but also multiplay number of objects in use, with no benefits whatsoever. Feb 15 '17 at 7:58
  • @ArturKępczyński, thanks for the comprehensive answer. Your points about disadvantages of extracting private method to external classes are valid but on the other hand, there are some benefits of this approach. For me feeling I need to test my private method is an indicator of breaking SRP. Also, after extracting it to external class I can 'safely' mock this object. In the end, classes are less coupled and easier to manage independently. External accessibility is still the issue and idk how to solve it. It's all opinionated and there is no golden rule here. Just wanted to put my 2 cents Feb 16 '17 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.