繁体   English   中英

powermockito 间谍私有无效方法调用

[英]powermockito spy private void method invocation

对于具有私有 void 方法的测试类,模拟该方法行为的正确方法是什么。 下面的解决方案改为调用该方法。

public class TestWizard {

    private void testOne(){
        throw new NullPointerException();
    }

    private void testTwo(){
        testOne();
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({TestWizard.class})
public class WTest {
    @Test
    public void testWizard() throws Exception {

        TestWizard wizard2 = Whitebox.newInstance(TestWizard.class);
        TestWizard wizard = Mockito.spy(wizard2);
        PowerMockito.doNothing().when(wizard, "testTwo");

    }
}

错误是:

java.lang.NullPointerException
    at tuk.pos.wizard.model.TestWizard.testOne(TestWizard.java:6)
    at tuk.pos.wizard.model.TestWizard.testTwo(TestWizard.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.powermock.reflect.internal.WhiteboxImpl.performMethodInvocation(WhiteboxImpl.java:1862)
    at org.powermock.reflect.internal.WhiteboxImpl.doInvokeMethod(WhiteboxImpl.java:824)
    at org.powermock.reflect.internal.WhiteboxImpl.invokeMethod(WhiteboxImpl.java:689)
    at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:401)
    at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:105)

使用PowerMockito.spy(...)而不是Mockito.spy(...)

使用 PowerMockito 2.0.5测试

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 org.powermock.reflect.Whitebox;

@RunWith(PowerMockRunner.class)
@PrepareForTest(WTest.TestWizard.class)
public class WTest {

    public class TestWizard {

        private void testOne(){
            throw new NullPointerException();
        }

        private void testTwo(){
            testOne();
        }
    }

    @Test
    public void testWizard() throws Exception {

        TestWizard spy = PowerMockito.spy(Whitebox.newInstance(TestWizard.class));
        PowerMockito.doNothing().when(spy, "testTwo");

        spy.testTwo();
    }
}

尝试将spies的使用限制为遗留代码。 在大多数其他情况下,重构应该是首选的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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