Mockito - 如何监视doAnswer

时间:2015-05-08 06:02:39

标签: java unit-testing junit mockito

这是我使用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

1 个答案:

答案 0 :(得分:3)

语法:

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

应该是:

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

仅使用when而不是spy致电spy.getCursor(),即可让Mockito有机会暂时停用getCursor ,以便您可以存根它而不需要调用真实的东西。虽然这在这里似乎并不重要,但Mockito坚持要求when之后调用doAnswer来保持这种模式。