我在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?
首先,如果要为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