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

问题描述:

请提供使用PowerMockito测试公共,静态,私有和私有静态方法的最小示例。如何设置PowerMockito来验证不同类型的方法是否被调用?

+1

你忘了问题...... – Morfic

+0

@Morfic这是在标题,如果我设置错了,请提供具体说明。 – KevinRethwisch

+0

我注意到了标题,但我发现很难理解你遇到问题的方式。你是否遇到异常?有没有按预期工作?等等...... – Morfic

这是一个极其简单的例子(“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"); 
    } 
} 

一些陷阱需要注意的:

  1. PowerMockito和双方的Mockito实施间谍()以及其他方法。确保为这种情况使用正确的课程。
  2. 错误地设置PowerMockito测试经常通过。确保测试可能会失败(在上面的代码中,通过注释“testable.a()”来检查)。
  3. 重写的PowerMockito方法将Class或Object作为参数分别用于静态和非静态上下文中。确保为上下文使用正确的类型。