I'm getting in trouble while trying to test a Singleton class X with
Junit4 in order to be able to test private (!!!) methods...
( X is also a thread and all its methods are private because it works
by itself, therefore there is no need for making them public )
It is quite simple to explain my problem:
Junit4 requests a default public constructor, but since X is a
singleton there is no public constructor...
There is a possibility to avoid the following error
"java.lang.Exception: Test class should have public zero-argument
constructor" ????????
(even with Parameterized will not work, since I do not need to call a
non-default constructor but the method "public static X getX()
{ ... }" in order to instantiate X )
Thank you all for any suggestion,
Andrea
Tom Hawtin - 12 Apr 2007 16:35 GMT
> I'm getting in trouble while trying to test a Singleton class X with
> Junit4 in order to be able to test private (!!!) methods...
Singletons don't get on with testing. If you like testing, avoid
singletons (and other static mutable variables).
To test private methods, I suggest refactoring to smaller, testable classes.
Tom Hawtin
Oliver Wong - 12 Apr 2007 18:35 GMT
> I'm getting in trouble while trying to test a Singleton class X with
> Junit4 in order to be able to test private (!!!) methods...
> ( X is also a thread and all its methods are private because it works
> by itself, therefore there is no need for making them public )
A common trick is to use the package-private (AKA default) visibility
instead of private, and put your test in the same package as the class
they're testing. This would also probably solve the problem of your
constructor being private (which you mentioned in the text I snipped).
- Oliver
a24900@googlemail.com - 12 Apr 2007 18:38 GMT
> It is quite simple to explain my problem:
> Junit4 requests a default public constructor
No, it doesn't.
Greg White - 12 Apr 2007 21:32 GMT
The point of JUnit is to test a class as it is seen by other, non derived
classes. As such you cannot test private methods, however you should not
need to directly test these anyway as testing the public methods should
ensure they get used/tested anyway.
> I'm getting in trouble while trying to test a Singleton class X with
> Junit4 in order to be able to test private (!!!) methods...
[quoted text clipped - 14 lines]
>
> Andrea