mockito中的AdditionalAnswers没有返回好的类型

时间:2015-01-13 16:13:49

标签: java mocking mockito stub

我尝试使用Mockito存根方法,但为了使其工作,我需要使用传递给此函数的参数。

这是我现在的代码,但它没有编译:

when(layer.createNewPlaylist("playlist1", Mockito.any(UUID.class))).thenReturn(new OnDemandPlaylist("playlist1", "", AdditionalAnswers.returnsArgAt(1)));

总而言之,我希望将第二个参数传递给返回的新对象。

现在,我有这个错误:

The constructor OnDemandPlaylist(String, String, Answer<Object>) is undefined

修改

我找到了使用&#34; old&#34;查询参数并在此处分享的方法。但我想知道使用thenReturn语法和AdditionalAnswers是否有更简单的方法。

when(layer.createNewPlaylist(Mockito.eq("playlist1"), Mockito.any(UUID.class)))
            .thenAnswer(new Answer<OnDemandPlaylist>() {
                 public OnDemandPlaylist answer(InvocationOnMock invocation) {
                     Object[] args = invocation.getArguments();
                     return new OnDemandPlaylist("playlist1", "", (UUID)args[1]);
                     }
                 });

1 个答案:

答案 0 :(得分:3)

此代码滥用了Mockito API:

when(layer.createNewPlaylist("playlist1", Mockito.any(UUID.class)))
    .thenReturn(new OnDemandPlaylist("playlist1", "", AdditionalAnswers.returnsArgAt(1)));
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                this is wrong

AdditionalAnswers.returnsArgAt(1)返回一个Answer,它将返回位置1的arg(其类型在编译时不知道),所以这有点预期构造函数上有编译错误,因为第三个参数是UUID,而不是Mockito Answer

AdditionalAnswers.returnsArgAt(1)用法记录在javadoc中:

This additional answer could be used at stub time using the then|do|willAnswer methods. For example :

given(person.remember(dream1, dream2, dream3, dream4)).will(returnsArgAt(3));
doAnswer(returnsArgAt(3)).when(person).remember(dream1, dream2, dream3, dream4);

您的解决方案实际上是做您想要的正确方法。即使让所有参数都匹配存根调用。请注意,使存根更具可读性对于将来的重构具有很大的优势:

when(layer.createNewPlaylist(eq("playlist1"), any(UUID.class))).then(playlistWithSameUUID);

public Answer<OnDemandPlaylist> playlistWithSameUUID() {
    return new Answer<OnDemandPlaylist>() {
                 public OnDemandPlaylist answer(InvocationOnMock invocation) {
                     Object[] args = invocation.getArguments();
                     return new OnDemandPlaylist("playlist1", "", (UUID)args[1]);
                     }
                 };
}