Java test class with many private methods

前端 未结 4 580
终归单人心
终归单人心 2021-01-11 17:42

I have a class that has the responsibility of importing contracts from a CSV to database.

The class itself has only one public method that starts the import and the

相关标签:
4条回答
  • 2021-01-11 18:22

    You can use reflection to achieve this. The Method class has a method called setAcessible(boolean) which enables you to call it even if declared as private/protected/default. See the example below:

    YourClass yourClassInstance = new YourClass();
    Method yourMethod = YourClass.class.getDeclaredMethod("yourMethod", null);
    yourMethod.setAccessible(true);
    Object[] parameters = new Object[1];
    parameters[0] = "A String parameter";
    Object result = yourMethod.invoke(yourClassInstance, parameters);
    
    0 讨论(0)
  • 2021-01-11 18:25

    Some people argue that you should only test your API (i.e. your public methods).

    A possible solution is to use package private so that only classes in the same package can access those methods.

    Personally, I wouldn't test private methods, I would focus on the public methods behaving as expected. If you feel your private methods carry too much weight, then perhaps they do and you should separate further the functionality.

    0 讨论(0)
  • 2021-01-11 18:31

    In theory, your private methods are being used ultimately by one of the public methods, or else they're not used at all. So typically you setup your tests to call the public methods with the necessary context so that it hits your private methods.

    The unit tests are primarily testing the compilation unit (i.e. the class). You can unit test methods directly but then they have to be public, which goes against having a nice clean API.

    So test your public method enough to hit all the private methods. Private methods are internal mechanics of the class, they don't need to be tested directly.

    0 讨论(0)
  • 2021-01-11 18:41

    If your class implements an interface you can make "public" all methods you like to tests, but do not add them to interface. In this case you will be able to access to these methods from test but not from you src.

    0 讨论(0)
提交回复
热议问题