3

I have a situation: I want to provide a service class with one functionality, for example: generating json file based on some params.. So I have one public method, and some private methods invoked by the public one. There are some private methods, and now I have a problem with unit testing them. I know possibilities (no test private method, make them public (NO!), refelctions,package private) , and the best is package private solution, but that service class is inside xx.service package and I only want to the one method be visible outside...

I am using Spring BOOT, and my question is : Maybe this is a bad approach with keeping private methods inside service class at all? Maybe move them to any kind of util classes? (To be honest that methods are kind of util methods..)

Please help :)

Kamil Gołąbek
  • 65
  • 1
  • 10

1 Answers1

2

If the public method under tests is using too many private methods and its simply hard to set-up / maintain the test cases, then it is probably time to extract some of that logic to specialized classes.

Ideally having one / two public methods.

Then you tests those helper classes in isolation (the tests should be small an simple now) and in the main service you simply inject them as dependencies. Then you mock those dependencies in the main service tests to your liking.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
  • Thanks for answer. But my private methods are short.. and they are specialized to specific use case realized by the one public method. For example: public File doSth(name){ if(existFileWithName(name)){ return modifyFile(name); } } private existFileWithName(name){...} priavte modifyFile(name){...} I can test public method, and it uses private methods... But I am trying TDD , and first want to write and test private method fucntionality... – Kamil Gołąbek Nov 23 '17 at 12:08
  • You never test private methods.. if you use a bit of private methods in the public method and you can still easily create tests cases (which are short and to the point) then your good.. when you have problems creating those tests.. naming them .. maintaining.. then its time to extract and create specialized classes – Maciej Kowalski Nov 23 '17 at 12:13