簡體   English   中英

Mockito-如何在doAnswer中監視Invocation參數

[英]Mockito - How to spy on Invocation argument in doAnswer

這是我使用Mockito編寫單元測試的第一天,我可能已經開始了一個復雜的練習。

下面是我的類結構,我正在為Class2.targetMethod()編寫測試。 Class1靜態方法修改傳入的對象,而不返回任何結果。

class Class1 {
    static void dbquery(OutParam out) {
        // Complex code to fill in db results in OutParam object
    }
}

class Class2 {
    void targetMethod() {
        OutParam p1 = new OutParam1();
        Class1.dbquery(p1);
        ResultSet rs = p1.getCursor();
        ...
    }
}

以下是我的測試設置:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Class1.class, Class2.class})
public class Class2Test {
    @Before
    public void setUp() throws Exception {

        PowerMockito.mockStatic(Class1.class);

        doAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Exception {
                OutParam result = (OutParam)invocation.getArguments()[1];
                OutParam spy = spy(result);
                ResultSet mockResult = mock(ResultSet.class);
                doReturn(mockResult).when(spy.getCursor());
                when(mockResult.getString("some_id")).thenReturn("first_id","second_id");
                when(mockResult.getString("name")).thenReturn("name1","name2");

                return null;
            }
        }).when(Class1.class, "dbquery", any());
    }
}

但是,測試失敗並出現以下異常-主要是由於“ doReturn”這一行。

關於此問題或我的方法完全錯誤的任何建議。

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, you naughty developer!
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

語法:

doReturn(mockResult).when(spy.getCursor());

應該:

doReturn(mockResult).when(spy).getCursor();

通過調用when只用spy ,而不是spy.getCursor()你給一個的Mockito機會暫時停用getCursor所以你可以存根時不調用真實的東西。 盡管這似乎在這里並不重要,但Mockito堅持要遵循doAnswer (etc) when調用模式。

暫無
暫無

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

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