Search code examples
javajunittestcase

Junit testing for following scenario


Consider the following class

public class Validator {

    boolean startValiadation(UserBean user){  
        //This method is visible inside this package only        
        return validateUser(user);           
    }

    private static boolean validateUser(UserBean user){
        //This method is visible inside this class only  
        boolean result=false;
        //validations here
        return result;
    }
}

Due to security requirement of above method I did code in above way. Now I want to wrote test cases using Junit. But generally a unit test is intended to exercise the public interface of a class or unit. Still I can use reflection to do some thing what I am expecting here. But I want to know is there any other way to achieve my goal?


Solution

  • But generally a unit test is intended to exercise the public interface of a class or unit.

    Well, I don't get too dogmatic about that. I find that often you can get much better testing depth if you're willing to be "white box" about it, and test non-public members. There's a sliding scale though - testing private members directly is relatively ugly, but you can test package private methods easily, just by making sure your test is in the same package as the class.

    (This approach also encourages package private classes - I find that if you're rigidly sticking to testing just the public API, you often end up getting into the habit of making all classes public and many methods public when actually they should be package private.)

    In this case, I would suggest you test via the startValiadation method. Currently that calls validateUser but ignores the result - I would assume that in the real code it calls the method and does something useful with the result, which would be visible from the test. In that case, you can just call startValiadation with various different User objects and assert which ones should be valid.