Usama K. Zafar
Usama K. Zafar

Reputation: 312

How to mock Kotlin Object in android?

I have an object in kotlin that controls the current user's session information. I want to mock the sign in method which has a call back.

While testing, I need to mock this method in the SessionController object.

object SessionController {

...

    fun signIn(username: String, password: String, signInCallBack: SignInCallBack) {
        sessionApi.attemptSignIn(username,password,object: SignInCallBack{
            override fun onSignInComplete() {
                signInCallBack.onSignInComplete()
            }

            override fun onErrorOccurred(errorCode: Int, errorMessage: String) {
                signInCallBack.onErrorOccurred(errorCode)
            }

        })
    }
    ....
}

The AndroidTest goes something like this:

@RunWith(AndroidJUnit4::class)
class LoginActivityTest {
  @Test
    fun loginErrorShowing() {
        test.tapUsernameField()
        test.inputTextinUsernameField("wrongusername")
        test.pressUsernameFieldIMEAction()
        test.inputTextinPasswordField("randomPassword")
        test.pressPasswordFieldIMEAction()

        Espresso.onView(ViewMatchers.withId(R.id.errorText)).check(ViewAssertions.matches(withText("Wrong Password")))
    }
}

Any suggestions/ideas as to how I can achieve this? I've read online to use Mockk for kotlin but have't been able to mock this method and invoke the appropriate callback. Any suggestions on improving the structure would also be appreciated.

Thanks

Upvotes: 3

Views: 2383

Answers (1)

muminers
muminers

Reputation: 1210

Well in my opinion you should made SessionController implementing an interface.

object SessionController: ISessionController {
    override fun signIn(username: String, password: String, signInCallBack: SignInCallBack) {
       (...)        
    }
}

interface ISessionController {
    fun fun signIn(username: String, password: String, signInCallBack: SignInCallBack)
}

This will give you a lot of possibilities to solve your problem like:

  • Dependency Injection
  • Test product flavour
  • Simple mockk() cration in your test code

It is a bit hard to give you very strict answer because you didn't post any UT code ;)


EDIT

It is hard to cover such a big topic as mocking in one post ;) Here are some great articles:

Creating Unit Tests you can always do simple:

presenter.sth = mockk<ISessionController>()

Upvotes: 4

Related Questions