Java test class with many private methods

前提是你 提交于 2019-12-01 15:07:50

问题


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 other methods are all private (because only the class itself will use, and they hold the logic).

I'm starting to make tests for this class using Spock and there are many private methods, how should I test it?

Should I turn them into public to test? Test only the main method, the public one?

Whats the best?


回答1:


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.




回答2:


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.




回答3:


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);



回答4:


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.



来源:https://stackoverflow.com/questions/27969920/java-test-class-with-many-private-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!