簡體   English   中英

Mockito驗證Class對象NotAMockException

[英]Mockito verify on Class object 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:傳遞給verify()的參數是Class類型的,不是模擬的!

誰能闡明我如何驗證在類對象上調用的方法?

非常感謝!

本。

這似乎不是應該通過模擬解決的問題。 我會選擇像這樣的具體測試:

@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(reallyStupidObject).doSomething()對象上調用verify ,即verify(reallyStupidObject).doSomething()

reallyStupidObject.getClass() -返回一個類而不是模擬對象。

您的模擬物是reallyStupidObject

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM