Skip to main content

Unit Testing, Javadoc, Private Constructors and Reflection

Posted by brunogh on April 13, 2011 at 9:15 PM PDT

Hello guys,

This post reflects a thought around a case that I have been experiencing. There a lot of things that involves implementing a spec and one of them is that you need to guarantee that you are not exposing more than it is available on the Javadoc.

There are a few static factory methods and no constructors, means public and protected, in our Javadoc scenario. So, you need to guarantee, by code, that there are only private constructors and nobody will cut them off.

So we create a unit test that assures there are not other constructors then private. Reflection is used for finding the constructors array and if there are no protected and public, zero should be returned.

FooTest.java:

         @Test public void testThereAreOnlyPrivateConstructors() {  

   Constructor[] constructors = Foo.class.getConstructors();    assertEquals(0, constructors.length); }

Foo.java: public class Foo {    private Foo() { }

   public static Foo createFoo(int s) {      //do something      return new Foo();    }            ... }

The thing is pretty much obvious, but the idea here was to shown something that does not happens everyday, but applies for a few interesting scenarios.

Cheers,
Bruno Ghisi

Related Topics >>

Comments

<p>Hi Bruno,</p> <p>your test method's name ...

Hi Bruno,
your test method's name <code>testThereAreOnlyPrivateConstructors</code> is misleading, since it actually asserts that there are no public constructors.
There could well be protected or package-accessible constructors, though.
I'm afraid there's no one-liner for what you want. You'd have to loop through <code>Foo.class.getDeclaredConstructors()</code> in order to find out about private ctors.

<p>Hello mcnepp, you are right! I misread the Javadoc and it ...

Hello mcnepp, you are right! I misread the Javadoc and it seems that the only way is using getDeclaredConstructors. Maybe something like above. Constructor[] constructors = Foo.class.getDeclaredConstructors(); for (int i = 0; i &lt; constructors.length; i++) { int modifier = constructors[i].getModifiers(); if(modifier != Modifier.PRIVATE) { fail(constructors[i].getName()+&quot; - &quot;+Modifier.toString(modifier)); } } assert(true); Thanks for the point! Bruno

<p>This is not a valid unit test. You have to use a static ...

This is not a valid unit test. You have to use a static source code analysies tool.

If you need that to understand the idea, please consider it ...

If you need that to understand the idea, please consider it included, but our Foo is not even complete.