将Java Mockito测试转换为Kotlin

将以下有效的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’的行会导致编译器错误:

Cannot infer a type for this parameter. Please specify it explicitly .

我试图像这样调整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 cannot be cast to org.mockito.stubbing.Answer

org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.foobar.ParkIdGenerationServiceTest.testSomething(ParkIdGenerationServiceTest.kt:92)

最初的目的是修改传递到存储库的save方法的实体并返回它.有什么想法怎么办?

解决方法:

将未经检查的演员表移至Answer< ParkIdMapping>进行getArgument调用.

另外,您需要添加辅助模拟方法. Mockito.any()在其验证函数中返回null,并且由于Kotlin Null安全功能,该模拟将抛出NPE.

像这样:

fun <T> any(): T {
    Mockito.any<T>()
    return uninitialized()
}

fun <T> uninitialized(): T = null as T

测试将是:

@Test
public fun test_correctParkIdMappingGeneration() {

    Mockito.`when`<ParkIdMapping>(parkIdMappingRepository.save(any())).thenAnswer(
        { invocation -> // compiler error
            val mapping = invocation.getArgument<ParkIdMapping>(0)
            mapping.id = 100L
            mapping
        }
    )
    val mapping = parkIdMappingRepository.save(ParkIdMapping("123"))

    assertEquals(100L, mapping.id)
}

关于Kotlin和Mockito互操作的未来阅读:https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791

上一篇:java-正确使用Mockito.reset()?


下一篇:java-在调用Mockito doNothing方法时调用实际方法