如何在 Kotlin 中对 Koin 组件 class 进行单元测试?

How to make Unit Test for Koin Component class in Kotlin?

我是单元测试的新手。我正在项目中使用 kotlin 进行单元测试。我应该测试 WelcomeFragment。我只是尝试使用 Mockito 库并尝试模拟这个 class。失败并出现错误

Mockito cannot mock this class:

如果我在没有模拟的情况下使用 PhoneHelper.isValid 方法然后得到错误

Koin has not started.

这个class使用PhoneHelper class如何在我的测试中成功测试PhoneHelper的.isValid方法?

WelcomeFragment.kt

 private fun checkEditText() {
        drawableChanges(
            PhoneHelper.isValid(
                mBinding.inputLogin.lifEdittext.text.toString(),
                mViewModel.mFormState.countryCode
            )
        )
    }

PhoneHelper.kt

import io.michaelrocks.libphonenumber.android.PhoneNumberUtil
import io.michaelrocks.libphonenumber.android.Phonenumber
import org.koin.core.KoinComponent
import org.koin.core.inject


object PhoneHelper : KoinComponent {
    private val mPhoneNumberUtil: PhoneNumberUtil by inject()

    fun isValid(gsmNo: String?, countryCode: String?): Boolean {
        val phoneModel = Phonenumber.PhoneNumber()
        phoneModel.nationalNumber = gsmNo?.toLongOrNull() ?: 0
        phoneModel.countryCode = if (countryCode?.contains("+")==true) countryCode?.removePrefix("+").toString()
            .toIntOrNull() ?: 90
        else 90
        return mPhoneNumberUtil.isValidNumber(phoneModel)
    }
}

WelcomeFragmentTest.kt

class WelcomeFragmentTest{

    val phonehelper = Mockito.mock(PhoneHelper::class.java)

    @Test
    fun `checkEditText Test`(){
        val phoneNo= "558887888"
        val bool = phonehelper.isValid(phoneNo,null)
        assertEquals(
            "false",
            bool
        )
    }

我通过编写测试代码解决了 Android UI 测试,所以它启动了 Android 设备模拟器,然后启动了 koin 库。

@RunWith(AndroidJUnit4::class)
class WelcomeFragmentAndroidTest {
    val phoneHelper = PhoneHelper
    private lateinit var scenario: FragmentScenario<WelcomeFragment>

@Test
fun checkEditTextTest(){
    val phoneNo = "5555555"
    val resultPhoneHelper = phoneHelper.isValid(phoneNo,null)
    Assert.assertEquals(false, resultPhoneHelper)
}