将以下有效的Java
测试转换为Kotlin
时遇到问题
@Test
public void testSomething() {
Mockito.when(parkIdMappingRepository.save(Mockito.any(ParkIdMapping.class))).thenAnswer(
(Answer<ParkIdMapping>) invocation -> {
ParkIdMapping mapping = invocation.getArgument(0);
mapping.setId(100L);
return mapping;
}
);
ParkIdMapping mapping = parkIdMappingRepository.save(new ParkIdMapping("123"));
assertEquals(new Long(100L), mapping.getId());
Intellij Idea向Kotlin进行的转换导致:
@Test
public fun test_correctParkIdMappingGeneration() {
Mockito.`when`(parkIdMappingRepository.save(Mockito.any(ParkIdMapping::class.java))).thenAnswer(
{ invocation -> // compiler error
val mapping = invocation.getArgument(0)
mapping.id = 100L
mapping
} as Answer<ParkIdMapping>
)
val mapping = parkIdMappingRepository.save(ParkIdMapping("123"))
assertEquals(100L, mapping.id)
}
但是,带有lambda参数'invocation'的行会导致编译器错误:
无法推断此参数的类型。请明确指定。
我试图像这样调整lambda
Mockito.`when`(parkIdMappingRepository.save(Mockito.any(ParkIdMapping::class.java))).thenAnswer(
{ invocation: InvocationOnMock ->
val mapping = invocation.getArgument(0) as ParkIdMapping
mapping.id = 100L
mapping
} as Answer<ParkIdMapping>
)
导致
java.lang.ClassCastException:com.foobar.ParkIdGenerationServiceTest $ test_correctParkIdMappingGeneration $ 1无法转换为org.mockito.stubbing.Answer
org.mockito.exceptions.misusing.UnfinishedStubbingException: 在此处检测到未完成的存根: -> com.foobar.ParkIdGenerationServiceTest.testSomething(ParkIdGenerationServiceTest.kt:92)
最初的目的是修改传递给save
的{{1}}方法的实体并返回它。有什么想法怎么办?
答案 0 :(得分:3)
将未选中的演员表移至Answer<ParkIdMapping>
调用。
此外,您需要添加辅助模拟方法。 getArgument
的验证函数返回null,并且由于Kotlin Null安全功能,该模拟程序抛出NPE。
赞:
Mockito.any()
测试将是:
fun <T> any(): T {
Mockito.any<T>()
return uninitialized()
}
fun <T> uninitialized(): T = null as T
关于Kotlin和Mockito互操作的未来阅读:https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791