Can PowerMock instantiate an inner class for test cases?

后端 未结 2 1892
暗喜
暗喜 2021-02-20 09:34

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

相关标签:
2条回答
  • 2021-02-20 09:53

    You can mock it like this:

    InnerClassType innerClass = (InnerClassType) Mockito.mock(
        Class.forName(EnclosingClass.class.getName() + "$InnerClass")
    );
    
    0 讨论(0)
  • 2021-02-20 09:54

    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.

    0 讨论(0)
提交回复
热议问题