2012-11-09 69 views
2

我似乎無法模擬使用powermock返回公共函數調用。NullPointerException在powermock中調用時方法

有人可以幫我嗎?

失敗的線是

PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA"));

的 「 when」 方法

代碼內

具體:

import static org.junit.Assert.fail; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.powermock.api.mockito.PowerMockito; 
import org.powermock.modules.junit4.PowerMockRunner; 

@RunWith(PowerMockRunner.class) 
public class PowermockTest { 

    private static class A { 

     private int number; 

     public A(int number) { 
      this.number = number; 
     } 

     public int getNumber() { 
      return number; 
     } 
    } 

    private static class B { 

     private int number; 
     private A a; 

     public B(int number) { 
      this.number = number; 
     } 

     public A getA() { 
      if (a == null) { 
       a = new A(number); 
      } 
      return a; 
     } 
    } 

    @Test 
    public void testOdrService() { 
     A aa = PowerMockito.mock(A.class); 
     try { 
      B bb = new B(3); 
      PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA")); 
     } catch (Exception e) { 
      fail("Exception in test. " + e.getMessage()); 
     } 
    } 

} 

PS:

更改代碼下面的作品,但它迫使我不想

B bb = new B(3); 
B bb1 = PowerMockito.spy(bb); 
PowerMockito.doReturn(aa).when(bb1).getA(); 
A mockedA = bb1.getA(); 

回答

5
PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA")); 

這句法是專門爲mocking static methods,而不是像mocking instance methods一個getA()虛擬對象的創建。

在大多數情況下,您不需要保留原始(窺探)的對象。

B bb = PowerMockito.spy(new B(3)); 
// work with bb as normal 
PowerMockito.doReturn(aa).when(bb).getA(); 
A mockedA = bb.getA(); // mockedA == aa 
+2

快速注:該文檔的'時()'方法傑夫提供的是在這裏:http://docs.mockito.googlecode.com/hg/latest/org/mockito只需直接與間諜互動/stubbing/Stubber.html#when(T)。附註:我確信上面的內容是簡化發佈的,但沒有任何內容似乎要求PowerMockito超過普通的舊Mockito。 –

+0

@Brian你是對的;我儘可能地複製了後記。這適用於'Mockito.spy(new B(3))'和'Mockito.doReturn(aa).when(bb).getA()'。 –

+0

哎呀,對不起 - 我的意思是作爲對OP的發佈代碼的評論。 –

相關問題