I have a class that has one public method (cheer for single responsibility principle) except within that method there is a try that lists about 20 method calls. In terms of testing and / or refactoring and testing, how would I go about this? I'm new to java. Looking for a better way to structure and test this code. Any suggestions / pointers to best practices would be appreciated! Thanks!
-
3Without seeing the code it is hard to give an answer to your question. – Leonard Brünings Nov 19 '13 at 18:02
-
Can you create several tests that call your public method with different parameters in order to test all of the paths inside your method? – hankd Nov 19 '13 at 18:03
3 Answers
Just because you have one public method doesn't mean you're following the Single Responsibility Principle. For example, you could write an entire project directly in the main
method if you wanted to. That main
would have many responsibilities.
What I'd do is test it through the public method if you can. If you can't, that suggests there's to many responsibilities in your class. You should discover these separate responsibilities and move them into other classes with their own public methods and then test the new class separately.

- 62,768
- 50
- 234
- 356
I agree with the previous answer. You should really consider having methods that accept parameters and perform a single action and return the result. If you can't break up your code into smaller segments, then you may add assertions directly to your code without use of a separate unit test class. Here is a link to show you how to add directly to your code. http://www.deitel.com/articles/java_tutorials/20060106/Assertions.html

- 776
- 8
- 21
Look at the specification for the method. (There is a specification, right?)
Every sentence or part-sentence in the specification that describes one thing that the method does should induce one test case - that is, one method in the test class that includes an assertion. If a sentence talks about behaviour in different scenarios (e.g. if the price field is > 0 then add a line to the statement, otherwise throw an IllegalArgumentException), then it might give you multiple test cases.
But seriously, 20 method calls within one method? That sounds to me like rather a fragile design. Please reconsider it.

- 77,785
- 15
- 98
- 110
-
new developer on old old project. I'm just looking for a more seasoned curries approach to solving this massive method problem. Thanks. – Somethingconcon Nov 19 '13 at 21:35
-
OK, but even if you don't have the specification, you should still be able to write some sentences about what the method is supposed to do, and base your test cases on that. Is the class that your unit testing an "old old" one, or something you've added? If it's the former, then why are you unit testing it? – Dawood ibn Kareem Nov 19 '13 at 22:07