dyesdyes dyesdyes - 1 year ago 87
Java Question

Refactoring to expose private methods for unit testing

I have a class that process a string and does many actions on it turn by turn.

Those actions need to be done in a specific order.


public String process(String stringToProcess) throws Exception {

processedString = process1(processedString);
processedString = process2(processedString);
processedString = process3(processedString);
processedString = process4(processedString);
processedString = process10(processedString);

return processedString;

I'm sure there is a better way to refactor this to make it cleaner, but most of all, I want to be able to unit test process1, process2 etc.

Note that process1, 2 etc... can be whether 2 line methods or big ones.

I would need the process methods to be somehow public to test them. Is there a design pattern that would achieve this?

I thought about using enums to achieve this, but I thought it was somehow making it more confusing. This implementation is not the best for sure, but at one glance, you know what's happening.

Edit: This approach is not too bad to me, but all the process methods should be private. And I want to unit test them.
I saw this question, so I can test them even if private, but the first step is to make sure it couldn't be done better.

Answer Source

You may take a look at http://www.codeproject.com/Articles/455228/Design-Patterns-3-of-3-Behavioral-Design-Patterns#Chain But maybe it's a kind of overkill for your task.

What I would do is to extract process1, process2 etc to separate classes. Then you can a) test them with unit tests separately b) inject them into your class and use them in process method in necessary order.

Take a look also to this post: Design Pattern for a multi-step algorithm Maybe you will get some ideas from there.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download