I'm attempting to test a class with a number of private classes (yes, I know this is generally considered poor practice for testability, but this question is not in regards to design principles). My class would look something like this:
public class EnclosingClass {
.
.
.
private class InnerClass implements InnerClassType {
public InnerClass(){ /* do stuff */}
public int InnerClassMethod();
}
}
InnerClassType
is a public interfaceI've tried instantiating the classes with powermock by doing:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
Constructor constructor = Whitebox.getConstructor(clazz, null);
InnerClassType innerClass = (InnerClassType) constructor.newInstance(null);
and also:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
InnerClassType innerClass = (InnerClassType) Whitebox.invokeConstructor(clazz);
However, on both attempts I get a ConstructorNotFoundException
Is it possible to instantiate these inner classes? If so, where am I going wrong?
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax: OuterClass outerObject = new OuterClass(); OuterClass.
A static inner class can be instantiated without the need for an instance of the outer class. In general, an Inner class is a part of nested class, called Non-static nested classes in Java. The types of inner classes are member inner class, anonymous inner class, and local inner class.
Because inner classes cannot declare static members other than compile-time constant fields, they cannot use the serialPersistentFields mechanism to designate serializable fields.
No, you cannot override private methods in Java, private methods are non-virtual in Java and access differently than non-private one. Since method overriding can only be done on derived class and private methods are not accessible in a subclass, you just can not override them.
You should be able to move past your ConstructorNotFoundExeception via the following mods to your first effort:
Class clazz = Whitebox.getInnerClassType(EnclosingClass.class, "InnerClass");
Constructor constructor = Whitebox.getConstructor(clazz, EnclosingClass.class);
InnerClassType innerClass = (InnerClassType) constructor.newInstance(new EnclosingClass());
Since your inner class is not static, it implicitly expects a "this" reference from the outer class. Using this method, looks like you have to get explicit with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With