我正在尝试设置类似于
GithubBrowserSample的UI测试,看起来示例项目只有Frag的模拟viewmodel而不是Activity的示例.
这是我的代码,我试图通过模拟viewmodel来测试Activity.但viewmodel未在Activity中的onCreate()之前设置.
@RunWith(AndroidJUnit4::class) class MainActivityTest { val viewmodel = mock(Mainviewmodel::class.java) @Rule @JvmField val activityRule = ActivityTestRule<MainActivity>(MainActivity::class.java,true,true) private val liveData = MutableLiveData<Resource<Object>>() @Before open fun setUp() { activityRule.activity.viewmodelFactory = createviewmodelFor(viewmodel) `when`(viewmodel.liveData).thenReturn(liveData) viewmodel.liveData?.observeForever(mock(Observer::class.java) as Observer<Resource<Object>>) liveData.postValue(Resource.success(Object())) } fun <T : viewmodel> createviewmodelFor(model: T): viewmodelProvider.Factory = object : viewmodelProvider.Factory { override fun <T : viewmodel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(model.javaClass)) { return model as T } throw IllegalArgumentException("unexpected model class " + modelClass) } } }
有人可以帮我解决这个问题吗?