Mockito的thenAnswer与Lambda

时间:2018-08-20 20:45:42

标签: scala mockito

所以我有这个模拟:

when(myMock.someMethod(anyString(), anyString(), anyString()))
                    .thenAnswer(new Answer[Path] {
                        override def answer(invocation: InvocationOnMock): Path =
                            temporaryFolder.getRoot.toPath.resolve(invocation.getArgument(2).asInstanceOf[String])
                    })

这很好用。但是,根据intelliJ的建议,进行一些在线阅读,似乎这样会更清洁:

when(myMock.someMethod(anyString(), anyString(), anyString()))
                    .thenAnswer((invocation: InvocationOnMock) => 
                         temporaryFolder.getRoot.toPath.resolve(invocation.getArgument(2).asInstanceOf[String]))

但是,当我尝试编译它时,出现编译错误:

Error:(56, 50) type mismatch;
 found   : org.mockito.invocation.InvocationOnMock => java.nio.file.Path
 required: org.mockito.stubbing.Answer[_]
                    .thenAnswer((invocation: InvocationOnMock) => temporaryFolder.getRoot.toPath.resolve(invocation.getArgument(2).asInstanceOf[String]))

为什么?我什至不理解此消息,难道不明白该参数是lambda吗?

我正在使用Mockito Core 2.7.19。

2 个答案:

答案 0 :(得分:2)

如果您使用Scala版本的Mockito(mockito-scala),则可以用更简单的方式编写它,因此您的代码如下:

when(myMock.someMethod(anyString(), anyString(), anyString()))
                .thenAnswer((invocation: InvocationOnMock) => 
                     temporaryFolder.getRoot.toPath.resolve(invocation.getArgument(2).asInstanceOf[String]))

将成为:

myMock.someMethod(*,*,*) shouldAnswer ((_: String, v: String) => temporaryFolder.getRoot.toPath.resolve(v)) 

请注意,我只是传递了一个标准的Scala函数,该函数将忽略第一个参数,并在不需要时完全省略第三个参数。

免责声明,我是该库的维护者

答案 1 :(得分:1)

使用lambda创建单一抽象方法类型是Scala 2.12中的一项新功能。正如您在注释中指出的那样,您正在使用2.11。考虑升级,否则您将无法使用长格式。

相关问题