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

时间:2016-02-25 21:45:40

标签: java junit mockito powermock powermockito

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

1 个答案:

答案 0 :(得分:0)

这是一个非常精简的示例(" SSCCE"),使用PowerMockito验证从另一种方法调用了四种类型的方法: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()以及其他方法。请务必使用正确的课程。
  2. 错误设置PowerMockito测试经常通过。确保测试可能失败(通过注释" testable.a()")在上面的代码中检查。
  3. 重写的PowerMockito方法将Class或Object作为参数分别用于静态和非静态上下文。确保为上下文使用正确的类型。