Search code examples
javaspringunit-testingspring-bootprivate-methods

Private methods in service layer


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


Solution

  • 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.