简体   繁体   中英

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

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.

Just needed to add OuterClass.s = s in the setUp() . No one tell my employer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM