如何在Android中模拟Kotlin对象? [英] How to mock Kotlin Object in android?

查看:61
本文介绍了如何在Android中模拟Kotlin对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在kotlin中有一个对象,用于控制当前用户的会话信息.我想模拟具有回调的登录方法.

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.

在测试时,我需要在SessionController对象中模拟此方法.

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

        })
    }
    ....
}

AndroidTest如下所示:

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

关于如何实现此目标的任何建议/想法?我已经在线阅读了有关将Mockk用于kotlin的信息,但无法模拟该方法并调用适当的回调.任何有关改进结构的建议也将不胜感激.

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.

谢谢

推荐答案

我认为您应该让SessionController实现接口.

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:

  • 依赖注入
  • 测试产品风味
  • 测试代码中的简单嘲笑(kock)创建

要给您一个非常严格的答案有点困难,因为您没有发布任何UT代码;)

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

编辑

很难在一个帖子中涵盖诸如嘲笑之类的大话题;)这里有一些很棒的文章:

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

这篇关于如何在Android中模拟Kotlin对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆