如何设置 PowerMockito 以验证不同类型的方法被调用?

How To Set Up PowerMockito To Verify Different Types of Methods Are Called?

请提供使用 PowerMockito 测试 public、public 静态、私有和私有静态方法的最少示例。

这是一个使用 PowerMockito 验证从另一个方法调用了四种类型的方法的极其精简的示例(“SSCCE”):public、public static、private , 和私有静态。

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");
    }
}

需要注意的一些陷阱:

  1. PowerMockito 和 Mockito 都实现了 spy() 以及其他方法。确保根据情况使用正确的 class。
  2. 错误地设置 PowerMockito 测试通常会通过。确保测试可以在应该失败的时候失败(通过注释掉 "testable.a()" 在上面的代码中检查)。
  3. 覆盖的 PowerMockito 方法采用 Class 或 Object 作为参数,分别用于静态和非静态上下文。确保为上下文使用正确的类型。