How to mock a Toast In Junit 5 in android

Viewed 163

I have a Method inside it I need do have a Custom Toast. I need to Unite Test. I tried To Mock It And It it Throwing Exception.

fun dummyFun(pContext : Context) {
        mViewHelper.showToastMessage(pContext, "Hello")
    }

This is My Custom Toast Method.

 val lToast = Toast(pContext)
            val lInflater: LayoutInflater = pContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            val lLayout = lInflater.inflate(R.layout.toast_view, (pContext as Activity).findViewById(R.id.toast_container))
            lLayout.findViewById<TextView>(R.id.toast_text).text = pMessage
            lToast.apply {
                setGravity(Gravity.CENTER, 0, 0)
                duration = Toast.LENGTH_SHORT
                view = lLayout
                show()
            }

And I tried to Unit Test it using Mockito and Junit 5 but it fails.

 `when`(mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).thenReturn(mLayoutInflater)
  doNothing().`when`(mViewHelper).showToastMessage(mContext, "Hello")
  val dummy = LoginViewModel(mLoginRepository, testCoroutineRule.pTestDispatcher)
  dummy.dummyFun(mContext)
0 Answers
Related