3

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

1 Answer 1

4

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>()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I have added the UT code snippet now as well. Could you share an example of how I can mock this interface?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.