Home > OS >  Mocked static outer class members are null when testing static inner class with PowerMockito
Mocked static outer class members are null when testing static inner class with PowerMockito

Time:12-21

I have a class that looks like this:

public class OuterClass {
    protected static Server s;

    public static class CrazyEvent implements Runnable {

        @Override
        public void run() {
            s.getSystemInfo();
        }
    }
}

It has a static member s of type Server, and an inner static class called CrazyEvent which extracts some info from the Server.

I'm trying to test this run() method in powermockito:

@RunWith(PowerMockRunner.class)
@PrepareForTest(OuterClass.class)
public class StaticInnerClassTest {
    private static class ServerMock extends Server {

        protected ServerMock(ServerConfig sc) {
            super(sc);
        }

        @Override
        public void start() {

        }
    }

    private static class ServerConfigMock extends ServerConfig {

    }

    @Mock
    ServerMock s = new ServerMock(new ServerConfigMock());

    @Mock
    UserMan um;

    @InjectMocks
    OuterClass.CrazyEvent ce = new OuterClass.CrazyEvent();

    @Before
    public void setUp() {

        MockitoAnnotations.initMocks(this);
        when(s.getUserMan()).thenReturn(um);

    }

    @Test
    public void testInnerClass() {
        ce.run();
    }

}

Let's walk through the code: I'm extending the actual Server object with ServerMock so I can override an annoying method that gets called in the constructor. My mocked Server object is s. Ideally, I'd like to inject this mock into the nested static inner class because it has to use it.

The problem is, when I call ce.run(), s is null and the mock is not properly injected. I'm pretty new to PowerMockito, and I've been struggling to find information on SO about this specific case.

Edit: There's a private static slf4j logger in the outer class that is null when called by the run() method in the inner class. I don't know how to instantiate it. I tried extending the outer class and making the logger protected and instantiating it that way but no luck.

Nevermind, I accidentally left in a call to PowerMockito.mockStatic() which was breaking everything 

CodePudding user response:

Just needed to add OuterClass.s = s in the setUp().

I also introduced an issue where I used PowerMockito.mockStatic(Outerclass.class) which was causing my static logger to become null. I removed this line.

  • Related