相关疑难解决方法(0)

AndroidViewModel和单元测试

我使用AndroidViewModelwith LiveData将Intent发送到IntentService并从EventBus接收事件。我需要意图和EventBus的应用程序上下文。

用本地测试测试AndroidViewModel类的最佳方法是什么?我可以从Robolectrics RuntimeEnvironment.application开始,但是似乎没有ShadowOf()用于AndroidViewModel来检查是否将正确的Intent发送到了正确的接收者。

也许可以通过Mockito使用我自己的模拟意图将其注入并注入到我的中AndroidViewModel,但这似乎不是很简单。

我的代码如下所示:

class UserViewModel(private val app: Application) : AndroidViewModel(app){
val user = MutableLiveData<String>()

...

private fun startGetUserService() {
    val intent = Intent(app, MyIntentService::class.java)
    intent.putExtra(...)
    app.startService(intent)
}

@Subscribe
fun handleSuccess(event: UserCallback.Success) {
    user.value = event.user
}
}
Run Code Online (Sandbox Code Playgroud)

肺动脉测试:

@RunWith(RobolectricTestRunner.class)
public class Test {
@Test
public void testUser() {
    UserViewModel model = new UserViewModel(RuntimeEnvironment.application)
    // how do I test that startGetUserService() is sending
    // the Intent to MyIntentService and check the …
Run Code Online (Sandbox Code Playgroud)

mockito robolectric android-testing

6
推荐指数
1
解决办法
1999
查看次数

访问存储库中的 appcontext 以获取共享首选项(架构)

根据官方指南,我目前正试图围绕 android 平台的架构组件进行思考:

在我的应用程序中,我目前需要存储一个字符串列表(名称)并在多个位置(活动和服务)访问它。我想到了两种可能的方法:

1)将它们以逗号分隔的形式存储在共享首选项中。
2)创建一个实体和房间表,名称为唯一列。

我更喜欢第一种方法,因为我只需要将名称作为一个字符串来执行 contains() 操作。为此,使用房间数据库似乎更麻烦。

我的具体问题是:将 appcontext 存储在存储库类(这是一个单例)中是否可以,或者我是否违反了任何约定/架构规则?或者实际上为此使用空间会更好吗?

android sharedpreferences android-room android-architecture-components

6
推荐指数
1
解决办法
2990
查看次数