Testing a Singleton with Junit4

G

Gira

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
 
T

Tom Hawtin

Gira said:
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
 
O

Oliver Wong

Gira said:
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
 
G

Greg White

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top