模拟私有方法时,PowerMock调用实际方法

时间:2016-01-20 12:35:57

标签: java mockito powermock powermockito

我正在使用PowerMock 1.6.2来模拟私有方法。此方法调用新的InitialContext(),显然在测试时不可用。我想模仿它返回一个简单的属性

MyFilter类

private Properties getProperties() throws NamingException{
    InitialContext ic = new InitialContext();
    return (Properties)ic.lookup("url/properties");
}

测试

@Test
public class MyTest extends PowerMockTestCase{

    private MyFilter mf;

    @BeforeClass
    public void beforeClass() {
        mf = PowerMockito.spy(new MyFilter ());
    }

    @Test
    public void testPrivate() throws Exception {
        Properties props = new Properties();
        props.put("allowed.ips", "127.0.0.1");
        PowerMockito.when(mf, "getProperties").thenReturn(props);
        mf.getProperties();
        ...
    }

此测试失败,因为此语句PowerMockito.when(mf, "getProperties").thenReturn(props);实际上调用了实际方法

at javax.naming.InitialContext.<init>(InitialContext.java:211)
at javax.naming.InitialContext.<init>(InitialContext.java:198)
at xxx.filter.MyFilter.getProperties(MyFilter.java:99)

我尝试过使用doReturn:

PowerMockito.doReturn(props).when(mf, "getProperties");

但它也失败了。

那么,我如何模拟私有方法并阻止它与PowerMock一起执行?

0 个答案:

没有答案