Re: JUnit FAQ suggests private methods bad design?

From: Mark Woyna (woyna_at_argonne.com)
Date: 12/09/03


Date: 9 Dec 2003 14:37:59 -0800


"Sylvain" <redhotsly@hotmail.com> wrote in message news:<3fd0e13b$1@news.totallyobjects.com>...
> RCM Wrote:
> > > One of my heuristics is: "tests trumps encapsulation". This means
> > > that I will make a private method public (or protected, or package) in
> > > order to unit test it properly.
>
> (Sorry for my empty post, I accidently hit send)
>
> FYI: C# allows invoking non public members through reflection. I use this
> feature to test private methods. I don't know if reflection in Java has this
> mecanism.
>
> -Sly

The easiest method I've found to test private methods is to make the
test class a static inner class. A static inner class has access to all
private methods, and instance variables, but does not introduce a deployment
dependency, i.e. the test class' .class file can be safely removed from the
deployed system, unlike a regular inner class. Having access to private
instance variables often makes writing the asserts easier, as one can
check the state of an object without having to introduce unnecessary getter
methods.

Since the inner class is technically part of the implementation of the class
under test, encapsulation is not violated, thus allowing one to have their
cake and eat it too. :-)

Another benefit to using inner classes is that they force the developer
to keep the test class up-to-date, or at least in a compilable state. Test
classes that are separate tend to become stale if TDD is not being used.

Mark



Relevant Pages

  • Re: unit testing private methods
    ... .I think this uses reflection to access private methods ... depend on and establish program invariants. ... complicated reflection fooferol unnecessary for unit-test purposes. ...
    (comp.lang.java.programmer)
  • Calling an internal constructor
    ... I know I can use reflection to call internal, protected, and private methods ... I'm so mad at MS about the CurrencyManager design it makes me want to ... derived from BindingManagerBase, and though the documentation has a "Note to ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: NUnit Test
    ... Not an easy way, look at reflection and you can get hold of private methods, ... but a bit of extra work to get there. ... I'm new to NUnit. ...
    (microsoft.public.dotnet.languages.csharp)