powermockito间谍私有无效方法调用

问题描述 投票:0回答:1

对于具有私有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)
unit-testing junit mockito powermock powermockito
1个回答
1
投票

使用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的使用限制为旧版代码。在大多数其他情况下,重构应该是首选解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.