0

I have a scenario where there is a public outer class and a private inner class. now i want to create an object of this private inner class for unit testing the methods in it.

public class MyOuterClass {
    public MyOuterClass() { }

    private class MyInnerClass {
        public MyInnerClass() { }
    }
}

This is the scenario where I am trying to create an object of "MyInnerClass" from some other test class. I found solution for creating object of class with private constructor but that is not what i required. please help me with this. thanks in advance.

user2786437
  • 33
  • 1
  • 6

2 Answers2

1

You have three options:

  1. Make the inner class package private (the default access level instead) and you can access it by putting your test code in the same package.

  2. Use reflection to access it by over-riding the access restriction.

  3. Rethink your architecture. It's possible you might need to directly test private inner classes but it would be more usual to test the outer class and by doing that also test the inner one.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • +1 for points #1 and #3 (particularly #3). Option #2 is just grim. – Duncan Jones Oct 08 '14 at 09:58
  • @Tim for using #3 For my scenario the inner class is a class extending Handler which overrides the handle message method, and this cannot be called directly unless u create the object of inner class. – user2786437 Oct 08 '14 at 10:38
  • @tim and we cannot change the access modifiers for all the cases where ever this happens right. so i think using reflection would be a better way. Can u please post a sample code snippet as iam new to reflection. – user2786437 Oct 08 '14 at 10:39
  • There are plenty of tutorials around, for example google found this: http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html – Tim B Oct 08 '14 at 10:41
  • In any of the tutorial, i did not found creating object of private inner class.. this link u suggested also has only about fields and methods and private constructors. but not what i required.. sorry..:\ – user2786437 Oct 08 '14 at 11:08
  • So do some searches...for example "java reflection access private inner class" gives as a first result http://stackoverflow.com/questions/14112166/instantiate-private-inner-class-with-java-reflection – Tim B Oct 08 '14 at 11:10
0

The whole concept of private objects is that it can only be accessed by the class that it's encapsulated in. You cannot directly create an instance of a private object from another class.

erad
  • 1,766
  • 2
  • 17
  • 26
  • If it is so, how can u achieve 100% code coverage in unit testing, for such types of code there are methods like reflection for accessing private members but iam not sure how to do that for this scenario. – user2786437 Oct 08 '14 at 10:34