被模拟的私有方法被调用而不是被模拟

Mocked private method is called instead of being mocked

我正在使用 PowerMockito 模拟私有方法。而是被嘲笑它被称为。我需要测试调用 privateMethod() 的 strangeMethod()。

这是我的 class 用于测试:

public class ExampleService {
    public String strangeMethod() {
        privateMethod();
        return "Done!";
    }

    private String privateMethod() {
        throw new UnsupportedOperationException();
    }
}

我的测试方法:

@Test
public void strangeMethodTest() throws Exception {
    ExampleService exampleService = PowerMockito.spy(new ExampleService());
    PowerMockito.when(exampleService, "privateMethod").thenReturn("");
    exampleService.strangeMethod();
}

作为测试的结果,我得到了 UnsupportedOperationException。这意味着调用了 privateMethod()。

当您使用 PowerMockito.spy(new ExampleService()); 时,所有方法调用首先将委托给真实 class 的实例。为什么你在第

行得到 UnsupportedOperationException

PowerMockito.when(exampleService, "privateMethod").thenReturn("");

如果你想避免调用真正的方法,那么使用 PowerMockito.mock( ExampleService.class);doCallRealMethod/thenCallRealMethod 作为不应该被模拟的方法。

这个例子显示私有方法被模拟:

Class:

public class ExampleService {
    public String strangeMethod() {

        return privateMethod();
    }

    private String privateMethod() {
        return "b";
    }
}

测试:

@PrepareForTest(ExampleService.class)
@RunWith(PowerMockRunner.class)
public class TestPrivate {

    @Test
    public void strangeMethodTest() throws Exception {
        ExampleService exampleService = PowerMockito.spy(new ExampleService());
        PowerMockito.when(exampleService, "privateMethod").thenReturn("a");
        String actual = exampleService.strangeMethod();

        assertEquals("a",actual);
    }

}