我正在尝试设置类似于
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) } } }
有人可以帮我解决这个问题吗?
解决方法
JUnit @Rules在@Before方法之前进行设置,因此您的活动在调用setUp()方法之前启动并开始其生命周期.要避免这种情况,请将false作为规则构造函数的第三个参数传递.这告诉它不要自动启动活动,因此您可以提前进行设置.
然后,您需要在运行测试之前手动启动活动.您可以创建val intent = Intent(InstrumentationRegistry.targetContext,MainActivity :: class.java)之类的intent,然后将其传递给activityRule.launchActivity(intent).