Java - is it possible to test a class that has a private constructor?
anonymous
2014-10-27 14:41:06 UTC
Java - is it possible to test a class that has a private constructor?
Three answers:
anonymous
2014-10-27 14:53:01 UTC
So i'm new to java and JUnit. I have succeeded in testing and initialising a class in a test file that has a public constructor. Is it possible to do the same with a class that has a private constructor?
Empire539
2014-10-27 15:56:54 UTC
It's possible, yes, but you would have to use reflection. See http://docs.oracle.com/javase/tutorial/reflect/
Of course, do you really even need to test a private constructor? Unit tests (according to several design philosophies) should test public code. Private methods and such should not explicitly be tested, as testing the public code which uses them will test the private code in itself.
xbox786
2014-10-28 21:09:39 UTC
You can test the class from within itself by running its main function. Otherwise, if the functions are static, you can call them without creating any object.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.