我正在尝试在Kotlin中使用Mockito。我创建了以下测试:

class HeroesDataSourceTest {

    @Mock
    lateinit var heroesRepository: HeroesRepository
    @Mock
    lateinit var params: PageKeyedDataSource.LoadInitialParams<Int>
    @Mock
    lateinit var callback: PageKeyedDataSource.LoadInitialCallback<Int, Heroes.Hero>

    val hero = Heroes.Hero(1, "superman", "holasuperman", 1, null, null)
    val results = Arrays.asList(hero)
    val data = Heroes.Data(results)
    val dataResult = Heroes.DataResult(data)

    val compositeDisposable = CompositeDisposable()

    lateinit var heroesDataSource: HeroesDataSource
    private val heroesPublishSubject = PublishSubject.create<Heroes.DataResult>()

    @Before
    fun initTest(){
        MockitoAnnotations.initMocks(this)

    }

    @Test
    fun testLoadInitialSuccess(){
        `when`(heroesRepository.getHeroes(ArgumentMatchers.anyInt())).thenReturn(heroesPublishSubject.singleOrError())
        heroesDataSource = HeroesDataSource(heroesRepository, compositeDisposable)
        val testObserver = TestObserver<Heroes.DataResult>()
        heroesDataSource.loadInitial(params, callback)
        heroesPublishSubject.onNext(dataResult)
        testObserver.assertComplete()
    }

}

但是,当我在when(heroesRepository.getHeroes(ArgumentMatchers.anyInt())).thenReturn(heroesPublishSubject.singleOrError())行中执行它时,它只是进入getHeroes方法而不是对其进行模拟(并且可以肯定的是,因为heroesRepository未初始化,因为它是模拟方法,所以该方法失败了)。我在Java中使用了无数次,但从来没有给我一个单一的问题。我必须在Kotlin中做什么才能正确模拟它?

编辑

这里我还放了HeroesRepository类
open class HeroesRepository {

    val privateKey = "5009bb73066f50f127907511e70f691cd3f2bb2c"
    val publicKey = "51ef4d355f513641b490a80d32503852"
    val apiDataSource = DataModule.create()
    val pageSize = 20

    fun getHeroes(page: Int): Single<Heroes.DataResult> {
        val now = Date().time.toString()
        val hash = generateHash(now + privateKey + publicKey)
        val offset: Int = page * pageSize
        return apiDataSource.getHeroes(now, publicKey, hash, offset, pageSize)
    }

    fun generateHash(variable: String): String {
        val md = MessageDigest.getInstance("MD5")
        val digested = md.digest(variable.toByteArray())
        return digested.joinToString("") {
            String.format("%02x", it)
        }
    }
}

最佳答案

无需添加其他依赖项,您可以将@Mock批注替换为某个地方的辅助函数:

inline fun <reified T> mock(): T =
        Mockito.mock(T::class.java)

// To avoid having to use backticks for "when"
fun <T> whenever(methodCall: T): OngoingStubbing<T> =
        Mockito.`when`(methodCall)

然后在您的测试中:
val heroesRepository: HeroesRepository = mock()

@Test
fun yourTest() {
    whenever(heroesRepository.getHeroes(ArgumentMatchers.anyInt()))
        .thenReturn(heroesPublishSubject.singleOrError())
}

就像你以前一样。这应该可行,因为您不希望Mockito处理@Mock lateinit var(似乎很费劲),而是自己实例化该模拟。

10-04 14:11