Как имитировать функцию kotlin карты? - PullRequest
1 голос
/ 09 мая 2020

Я пытаюсь заглушить kotlin расширение .map:

private fun stubGetUsers(users: List<User>) {
   val genericRawResult = mock<GenericRawResults<User>>()
   whenever(genericRawResult.map { User() }).thenReturn(users)

   usersDao.stub { on { it.queryRaw("", RawRowMapper { _, _ -> User() }) }.doReturn(genericRawResult) }
}

Когда я запускаю тест, я получаю NullPointerException:

public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) -> R): C {
    for (item in this)
        destination.add(transform(item))
    return destination
}

в строке: for (item in this)

Итак, я попытался имитировать функцию _Collections.kt class mapTo:

val destination = arrayListOf<User>()

whenever<List<User>>(genericRawResult.mapTo(destination) { User() }).thenReturn(destination)

Но все равно получаю сообщение об ошибке:

java.lang.NullPointerException
    at com.myapp.UserRepositoryTest.stubGetUsers(UserRepositoryTest.kt:144)
    at com.myapp.UserRepositoryTest.testGetAllUsers(UserRepositoryTest.kt:66)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

Чтобы получить подробную ошибку, я сделал следующие изменения:

genericRawResult.stub { onGeneric { it.mapTo(arrayListOf()) { User() } }.doReturn(arrayListOf()) }
genericRawResult.stub { on { it.map { User() } }.doReturn(users) }

И вот ошибка, которую я получаю:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
ArrayList cannot be returned by iterator()
iterator() should return Iterator
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
...