Search code examples
javaencapsulationnested-class

Non-Public Static Nested Class?


I am trying to write tests for a piece of code that uses the inner class of the following object as an input (I've generalized the names).

public class MockOuterClass implements OuterClass, Mock {

  static class MockInnerClass implements InnerClass {
  //fields and methods of the nested class
  }

//methods of the outer class
}

Now since the inner class does not have a visibility tag, it defaults to "protected." Here lies my issue: since my tests and source code are in separate packages, how can I create an instance of this inner object? I attempted this:

MockOuterClass.MockInnerClass test = new MockOuterClass.MockInnerClass();

When I do this, Eclipse says that this line is unacceptable (which I assumed was the case, but it was wishful thinking) since MockInnerClass defaults to protected and thus cannot be used outside its package. Is there a way I can use this class somehow? I did not write the source code, so I am unsure if the lack of a "public" tag on the inner class was intentional or the programmer's mistake.

Thank you in advance.


Solution

  • A bit of an aside, not an actual answer, but I have always put my tests into the same package as the classes being tested. At least, as much as possible, there are a few very rare cases where this is impossible.

    Why are you using a different package? Is there a good reason to do so?

    Now, back to an answer, if you insist on testing from a separate package, unless MockOuterClass exposes some method to construct (or expose) the MockInnerClass, you are stuck. (I guess you could try using Reflection but that is getting desperate.) However, as several have commented, the author of the class "intended" for the inner class to be hidden, a. la. Kent Beck.

    In other words, if you follow Kent Beck, you should be writing tests that target MockOuterClass, NOT MockInnerClass. The inner class is a "non public detail".