4

So our stack is on Spring, and say Class Wizard is only ever called from a UI change. On the xhtml its called like this:

`<.....onchange="changeValue()" value="wizard.type.name">`

The class is never instantiated anywhere in the code, and the only constructor in the class is:

public Wizard(){}

And say getName() calls a private method getWizardWeapon() - how do i go about testing getWizardWeapon() in junit in a separate project (say TestWizard but in the same workspace)?

bouncingHippo
  • 5,940
  • 21
  • 67
  • 107
  • How about instantiate it in JUnit and use reflection? See http://stackoverflow.com/questions/34571/how-to-test-a-class-that-has-private-methods-fields-or-inner-classes – dejvuth Jun 18 '15 at 13:15
  • 1
    test 'interface' which is visible outside of a class. So getName in this case. Otherwise you may couple test too much to your implementation. – hi_my_name_is Jun 18 '15 at 13:24

2 Answers2

4

You shouldn't have to test private methods. Tests should only go through the public interface methods. So your tests should all go through getName().

By not testing private methods, your tests are less fragile because if you ever changed your private method, the test would break. It is so much easier to maintain and refactor classes knowing that modifying private methods shouldn't break anything as long as the public methods still do the right thing (which are all covered by tests).

From an API perspective I also find it weird that getName() also needs to getWizardWeapon(). unless the weapon is part of the name (which is weird).

If you can't exercise all code paths through your private methods by only calling public methods, maybe you have dead code that can be removed?

dkatzel
  • 31,188
  • 3
  • 63
  • 67
2

As an addition to @dkatzel answer: if you actually need to test some implementation details, but don't want to expose them to the outer world, make getWizardWeapon() not private, but package private and put your test cases in the same package (but of course in separate source directory like main/com/example/Wizard and test/com/example/TestWizard).

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334