2016-05-29 67 views
0

我有下一個JUnit測試,但是當我執行它時會拋出「對象不是聲明方法的實例」。 它可能是什麼?JUnit異常「對象不是聲明方法的實例」

@Test 
    public void testCopiarByteArray() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, InstantiationException, UnsupportedEncodingException{ 
     String expected = "prueba"; 
     String mensaje = "prueba"; 

     DataReader datareader = new DataReader(null, null, 100, "="); 

     Method copiarByteArray = datareader.getClass().getDeclaredMethod("copiarByteArray", byte[].class, int.class); 
     copiarByteArray.setAccessible(true); 

     byte[] copia = (byte[]) copiarByteArray.invoke(mensaje.getBytes(), mensaje.getBytes().length); 

     String actual = new String(copia, "UTF-8"); 

     assertEquals("failure - encription not correctly encript", expected, actual); 
    } 

回答

1

.invoke的第一個參數應該是要調用該方法的對象的實例。

所以不是:

byte[] copia = (byte[]) copiarByteArray.invoke(mensaje.getBytes(), mensaje.getBytes().length); 

您需要添加datareader作爲第一個參數:

byte[] copia = (byte[]) copiarByteArray.invoke(datareader, mensaje.getBytes(), mensaje.getBytes().length); 
0

檢查反射API上的javadoc。

你必須通過對象對作爲第一個參數調用你的方法;然後是「實際」方法參數。

您的代碼嘗試在mensaje.getBytes()上執行方法;這當然不起作用。