1
請提供使用PowerMockito測試公共,靜態,私有和私有靜態方法的最小示例。如何設置PowerMockito來驗證不同類型的方法是否被調用?
請提供使用PowerMockito測試公共,靜態,私有和私有靜態方法的最小示例。如何設置PowerMockito來驗證不同類型的方法是否被調用?
這是一個極其簡單的例子(「SSCCE」),它使用PowerMockito來驗證從另一種方法調用的四種類型的方法:public,public static,private和private static。
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(com.dnb.cirrus.core.authentication.TestableTest.Testable.class)
public class TestableTest {
public static class Testable {
public void a() {
b();
c();
d();
e();
}
public void b() {
}
public static void c() {
}
private void d() {
}
private static void e() {
}
}
Testable testable;
// Verify that public b() is called from a()
@Test
public void testB() {
testable = Mockito.spy(new Testable());
testable.a();
Mockito.verify(testable).b();
}
// Verify that public static c() is called from a()
@Test
public void testC() throws Exception {
PowerMockito.mockStatic(Testable.class);
testable = new Testable();
testable.a();
PowerMockito.verifyStatic();
Testable.c();
}
// Verify that private d() is called from a()
@Test
public void testD() throws Exception {
testable = PowerMockito.spy(new Testable());
testable.a();
PowerMockito.verifyPrivate(testable).invoke("d");
}
// Verify that private static e() is called from a()
@Test
public void testE() throws Exception {
PowerMockito.mockStatic(Testable.class);
testable = new Testable();
testable.a();
PowerMockito.verifyPrivate(Testable.class).invoke("e");
}
}
一些陷阱需要注意的:
你忘了問題...... – Morfic
@Morfic這是在標題,如果我設置錯了,請提供具體說明。 – KevinRethwisch
我注意到了標題,但我發現很難理解你遇到問題的方式。你是否遇到異常?有沒有按預期工作?等等...... – Morfic