如何使用Koin在RoboElectric测试中注入模拟的ViewModel

问题描述 投票:1回答:1

我在Android开发中还很陌生,目前,我正在测试Roboelectric和Koin的基本活动。

代码:

class SplashActivity : AppCompatActivity() {
    private val viewModel: LoginViewModel by viewModel()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash)

        Stetho.initializeWithDefaults(this)

        val user = viewModel.getPersistedUser()

        if (user != null) {
            viewModel.setUser(user)
            startActivity(HomeActivity.getStartIntent(this))
        } else {
            startActivity(LoginActivity.getStartIntent(this))
        }
    }
}

val appModule = module(override = true) {
    ...

    viewModel<LoginViewModel>()
}

现在,我在测试中要做的就是注入模拟版本的viewModel以模拟方法getPersistedUser的响应。

我该如何使用Roboelectric和Koin?

android android-testing robolectric koin
1个回答
0
投票

首先,如果要为SplashActivity编写UI测试。更好地使用Expresso测试框架(https://developer.android.com/training/testing/espresso

第二,如果您想在测试中使用Koin模拟视图模型,可以加载Koin模块,然后声明您的viewmodel模拟,代码将类似如下:>

class SplashActivityTest : AutoCloseKoinTest() {

    private val viewModel: LoginViewModel by inject()

    @Before
    fun before() {
        koinApplication {
            loadModules(appModule)
        }
        declareMock<LoginViewModel> {
            given(getPersistedUser()).willReturn { User(username, password) }
        }
    }

    @Test
    fun loadCurrentUserWhenActivityInit() {
        // verify your test here 
    }
}

更多详细信息,请点击https://start.insert-koin.io/#/getting-started/testing

© www.soinside.com 2019 - 2024. All rights reserved.