2016-02-25 74 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作爲參數分別用於靜態和非靜態上下文中。確保爲上下文使用正確的類型。
相關問題