Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么Powermockito调用我的模拟方法?_Java_Junit4_Powermockito - Fatal编程技术网

Java 为什么Powermockito调用我的模拟方法?

Java 为什么Powermockito调用我的模拟方法?,java,junit4,powermockito,Java,Junit4,Powermockito,我想模拟从我的测试方法调用的私有方法,但不是模拟,而是PowerMockito调用toMockMethod,我得到了NPE。 toMockMethod在同一个类中 @RunWith(PowerMockRunner.class) public class PaymentServiceImplTest { private IPaymentService paymentService; @Before public void init() { payment

我想模拟从我的测试方法调用的私有方法,但不是模拟,而是PowerMockito调用toMockMethod,我得到了NPE。 toMockMethod在同一个类中

@RunWith(PowerMockRunner.class)
public class PaymentServiceImplTest {

    private IPaymentService paymentService;

    @Before
    public void init() {
        paymentService = PowerMockito.spy(Whitebox.newInstance
                (PaymentServiceImpl.class));
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        ...
        PowerMockito.doReturn(mockedReturn)
                .when(paymentService,
                      "toMockMethod",
                      arg1, arg2);
    }
}

这是正常情况吗?如果调用了mock方法,对它有什么意义?

要使用PowerMock为类启用静态或非公共模拟,应将该类添加到注释
@PrepareForTest
。在您的情况下,它应该是:

@RunWith(PowerMockRunner.class)
@PrepareForTest(PaymentServiceImpl.class)
public class PaymentServiceImplTest {

    private IPaymentService paymentService;

    @Before
    public void init() {
        paymentService = PowerMockito.spy(Whitebox.newInstance
                (PaymentServiceImpl.class));
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        ...
        PowerMockito.doReturn(mockedReturn)
                .when(paymentService,
                      "toMockMethod",
                      arg1, arg2);
    }
}

我要给我未来的自己留下第二个答案。这里还有另一个问题。如果要调用Static.method,请确保“method”实际上是在Static中定义的,而不是在层次结构上定义的

在我的例子中,代码名为Static.method,但Static是从StaticParent扩展而来的,“method”实际上是在StaticParent中定义的

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticParent.class)
公共类YourTestClass{
@以前
公共init(){
mockStatic(StaticParent.class);
when(StaticParent.method(“”)。thenReturn(yourReturnValue);
}
}
公共类ClassYourTest{
公共方法(){
Static.method(“”;//返回您的returnValue
}

当您想测试服务时,通常会模拟其与私有方法交互的依赖项,而不是模拟私有方法。@Compass我测试一个公共方法,该方法调用同一类的私有方法请参见