2012-11-01 260 views
2
private boolean isEmpty(Object[] array) { 
    if (array == null || array.length == 0) 
     return true; 
    for (int i = 0; i < array.length; i++) { 
    if (array[i] != null) 
     return false; 
    }   

    return true; 
} 

@Test 
public void testIsEmpty() { 
     //where is an instance of the class whose method isEmpty() I want to test. 
    try { 
     Object[] arr = null; 
     assertTrue((Boolean)(Whitebox.invokeMethod(where, "isEmpty", new Class<?>[]{Object[].class}, arr))); 

     arr = new Object[0]; 
     assertTrue((Boolean)(Whitebox.invokeMethod(where, "isEmpty", new Class<?>[]{Object[].class}, arr))); 

     arr = new Object[]{null, null}; 
     assertTrue((Boolean)(Whitebox.invokeMethod(where, "isEmpty", new Class<?>[]{Object[].class}, arr))); 

     arr = new Object[]{1, 2}; 
     assertFalse((Boolean)(Whitebox.invokeMethod(where, "isEmpty", new Class<?>[]{Object[].class}, arr))); 
    } catch (Exception e) { 
     fail(e.getMessage()); 
    }  
} 

問題的方法:java.lang.AssertionError:錯誤的參數數目PowerMock:使用Whitebox.invokeMethod(...)正確用於拍攝對象[]作爲PARAM

研究: 1。最初,我嘗試過: invokeMethod(Object tested,String methodToExecute,Object ... arguments)

第二,第三和第四個invokeMethod()失敗。 (錯誤:未找到給定參數的方法)

我認爲這可能是由於PowerMock不能推斷正確的方法;因此,我切換到: 的InvokeMethod(對象測試,字符串methodToExecute,類[] argumentTypes,對象...參數)

  1. 父類具有在子類推翻用的isEmpty()方法一個精確重複的isEmpty()方法。 (遺留代碼)不存在其他不同簽名的isEmpty()方法。有很多采用參數的方法,但沒有其他採用Object []的方法(例如,沒有采用Integer []作爲參數的方法)。

  2. 在上述第二個assertTrue語句之前,更改爲arr = new Object [1]會使該assert語句通過。

任何幫助,非常感謝。謝謝!

回答

4

認爲應該通過強制轉換爲客體的爭論工作,爲了讓Java把它作爲一個參數,而不是對應Object...參數數組:

Whitebox.invokeMethod(where, "isEmpty", new Class<?>[]{Object[].class}, (Object) arr); 

測試案例:

public static void main(String[] args) { 
    foo(new Object[] {"1", "2"}); // prints arg = 1\narg=2 
    foo((Object) (new Object[] {"1", "2"})); // prints args = [Ljava.lang.Object;@969cccc 
} 

private static void foo(Object... args) { 
    for (Object arg : args) { 
     System.out.println("arg = " + arg); 
    } 
} 
+0

這工作完美!謝謝。 :) – kchang