2016-02-25 94 views

回答

0

这是一个极其简单的例子(“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作为参数分别用于静态和非静态上下文中。确保为上下文使用正确的类型。
相关问题