简体   繁体   中英

How to mock a protected static inner class with PowerMockito

I have a public outer class with a protected static inner class that I need to mock out for unit testing. We are using Mockito and PowerMockito but I have not been able to find anything in this vein during my searches. Does anyone have any ideas? Refactoring the inner class to be outside of the class and be public or anything of the sort is out of the question as of now as well.

Given a structure similar to

public class OuterClass {

    public OuterClass() {
        new InnerClass();
    }

    protected static class InnerClass {
        public InnerClass() {
            throw new UnsupportedOperationException("Muahahahaha!"); // no touchy touchy!
        }
    }
}

... you should be able to do the following

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertNotNull;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.whenNew;

@RunWith(PowerMockRunner.class) // delegate test running to PowerMock
@PrepareForTest(OuterClass.class) // mark classes for instrumentation so magic can happen
public class InnerClassTest {

    @Test
    public void shouldNotThrowException() throws Exception { // oh, the puns!
        // make a mockery of our inner class
        OuterClass.InnerClass innerClassMock = mock(OuterClass.InnerClass.class);

       // magically return the mock when a new instance is required
       whenNew(OuterClass.InnerClass.class).withAnyArguments().thenReturn(innerClassMock);

        // yey, no UnsupportedOperationException here!
        OuterClass outerClass = new OuterClass();
        assertNotNull(outerClass);
    }
}

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