2014-05-15 83 views
0

我試圖寫一個測試下列靜態方法:驗證的Mockito對Class對象NotAMockException

public static Field getField (Class<?> type, String fieldName) { 
    for (Field field : type.getDeclaredFields()) { 
     if (field.getName().equals(fieldName)) { 
      return field; 
     } 
    } 

    if (type.getSuperclass() != null) { 
     return getField(type.getSuperclass(), fieldName); 
    } 

    return null; 
} 

這是我的測試代碼:

@Test 
public void getFieldTest() { 
    class StupidObject { Object stupidField; } 
    class ReallyStupidObject extends StupidObject { Object reallyStupidField; } 
    ReallyStupidObject reallyStupidObject = mock(ReallyStupidObject.class); 
    // -------------------------------------------------- 
    Field field = FSUtils.getField(reallyStupidObject.getClass(), "stupidField"); 
    // -------------------------------------------------- 
    verify(reallyStupidObject.getClass()).getDeclaredFields(); 
    verify(reallyStupidObject.getClass()).getSuperclass(); 
    verify(reallyStupidObject.getClass().getSuperclass()).getDeclaredFields(); 
    verify(reallyStupidObject.getClass().getSuperclass(), never()).getSuperclass(); 
    assertEquals(field.getName(), "stupidField"); 
} 

導致這個錯誤:

org.mockito.exceptions.misusing.NotAMockException: Argument passed to verify() is of type Class and is not a mock!

任何人都可以闡明我如何驗證在Class對象上調用的方法嗎?

非常感謝!

本。

回答

1

這似乎不是一個嘲笑應該解決的問題。我會選擇這樣一個具體的測試:

@Test 
public void getFieldTest() { 
    class StupidObject { Object stupidField; } 
    class ReallyStupidObject extends StupidObject { Object reallyStupidField; } 

    // test the right field is found in the right class 
    testFieldFind("stupidField", ReallyStupidObject.class, 
      StupidObject.class); 
    testFieldFind("reallyStupidField", ReallyStupidObject.class, 
      ReallyStupidObject.class); 

    // check that non-existent fields return null 
    assertNull(FSUtils.getField(ReallyStupidObject.class, "fooballs")); 
} 

private static void testFieldFind(String fieldName, Class<?> classToSearch, 
     Class<?> expectedDeclaringClass) { 
    Field field = FSUtils.getField(classToSearch, fieldName); 
    assertEquals(fieldName, field.getName()); 
    assertEquals(expectedDeclaringClass, field.getDeclaringClass()); 
} 

至於爲什麼你的原始代碼的失敗 - 你必須調用verify你的嘲笑對象,即verify(reallyStupidObject).doSomething()

+0

這看起來不錯,謝謝! – Ben

0

reallyStupidObject.getClass() - 返回類而不是模擬對象。你的模擬是非常愚蠢的對象。

+0

我明白,但不可能嘲笑類,因此這是一個解決方法的破解嘗試。 – Ben

+0

也許這可以幫助你:http://stackoverflow.com/questions/12251424/mocking-getclass-method-with-powermockito – Lexandro