我们如何将模拟的 viewModel 注入到 Activity 中进行 espresso 测试?使用declareMock
我在 Test 类中获取模拟对象,但 Activity 接收常规 viewModel 对象。
@RunWith(AndroidJUnit4::class)
class SomeActivityTest : KoinTest {
@Rule
@JvmField
val rule = ActivityTestRule(SomeActivity::class.java, true, true)
val viewModel: MyViewModel by inject()
@Before
fun setup() {
declareMock<MyViewModel>(isFactory = true, binds = listOf(ViewModel::class))
}
@After
fun cleanUp() {
stopKoin()
}
@Test
fun shouldHaveTextViewVisible() {
`when`(viewModel.sayHello())
.thenReturn("hello view-model")
onView(withId(R.id.tv_homescreen_message))
.check(matches(isDisplayed()))
onView(withId(R.id.tv_homescreen_message))
.check(matches(withText("hello view-model")))
}
}