Search code examples
javajunitmockitopowermockpowermockito

Testing a method which uses an List of objects of a private static class


I have method that I want to test. It's input parameter is a list of objects of a private static class

Class Invoker{

   public String method1(String inp){

   ArrayList<InnerClass> params = new ArrayList<>();
   params.add(new InnerClass("some value"));
   String op = method2(params);
   //other implementation
  }

   public String method2(ArrayList<InnerClass> list){

     //method implementation
  }

   private static class InnerClass {
      private String var1;

          public InnerClass(String str){
          super();
          this.str = str;
         }
   }
}

Now, I want to write a test case for method 'method1'. The issue I'm facing is that while testing, I'm not able to create the ArrayList in the test class.


Solution

  • You are going down the wrong rabbit hole here.

    Making an inner class private communicates to your readers (and the compiler btw) that this inner class in intended to only be used within the outer enclosing class. End of story.

    Using the class name within the signature of a public method simply doesn't make sense therefore.

    Of course, you could theoretically use reflection to work around this (until maybe Java 9 modules get into your way), but as said: doing so is a waste of time.

    If you need to use things outside your class, don't make them private. So consider turning them package protected. Then users inside the same package have access, and so have unit tests that should live in the same package).