Search code examples
androidunit-testingkotlinmockitokoin

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


I am new with Unit testing. I am doing Unit test with kotlin in a project. I should test WelcomeFragment. I just tried to use Mockito library and tried to mock this class. That failed with error

Mockito cannot mock this class:

If I use PhoneHelper.isValid method without mocking then getting error

Koin has not started.

This class use PhoneHelper class How can I test successfully .isValid method of PhoneHelper in my test?

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
        )
    }

Solution

  • I solved with writing test code as Android UI test, So it start Android device emulator and then koin library started.

    @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)
    }