我的应用程序首先通过http请求(Retrofit)加载项目列表,然后在RecyclerView中显示。
很好。
现在,我编写了许多Espresso的测试来检查显示加载列表结果的屏幕(活动= TradersActivity
)。
因此,我通过okhttp3.mockwebserver.MockResponse
来模拟加载项,并将其放入@Before方法。
结果是先加载数据,然后开始进行浓缩咖啡测试(例如itemList_isDisplayed()
)
这是Espresso的测试片段:
i
mport okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
@RunWith(AndroidJUnit4::class)
class TradersActivityTest {
@Rule
@JvmField
var tradersIntentTestRule = IntentsTestRule(TradersActivity::class.java, false, false)
@Before
fun setup() {
mockServer = MockWebServer()
mockServer.start(8081)
mockServer.enqueue(MockResponse()
.setResponseCode(200)
.setBody(FileUtil.getStringFromFile(context, DEFAULT_TRADERS_LIST)));
tradersIntentTestRule.launchActivity(Intent())
}
@Test
fun toolBar_height() {
onView(withId(R.id.toolBar))
.check(matches(withHeightResId(R.dimen.tool_bar_height)))
}
@Test
fun itemList_isDisplayed() {
onView(withId(R.id.tradersRecyclerView))
.perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(checkItemCount));
onView(withRecyclerView(R.id.tradersRecyclerView).atPosition(checkItemCount))
.check(matches(isDisplayed()))
}
@Test
fun itemList_BaseisDisplayed() {
onView(withId(R.id.tradersRecyclerView))
.perform(scrollToPosition<RecyclerView.ViewHolder>(checkItemCount));
onView(withRecyclerView(R.id.tradersRecyclerView).atPositionOnView(checkItemCount, R.id.baseTextView))
.check(matches(isDisplayed()))
}
}
好。很好。
但是现在我要编写测试,以在HTTP响应返回错误(例如 http status = 400 )时检查是否显示吐司。 然后添加此测试:
@Test
fun network_clientError_showToast() {
mockServer.enqueue(MockResponse()
.setResponseCode(400))
tradersIntentTestRule.launchActivity(Intent())
onView(withText(R.string.client_error)).inRoot(ToastMatcher()).check(matches(isDisplayed()))
}
您可以看到此测试“ network_clientError_showToast
”首先是存根错误响应,然后是启动活动。
结果,当我开始测试时,出现错误:
java.lang.RuntimeException: Could not launch intent Intent { flg=0x10000000 cmp=com.myproject.debug/com.myproject.ui.activity.TradersActivity } within 45 seconds. Perhaps the main thread has not gone idle within a reasonable amount of time? There could be an animation or something constantly repainting the screen. Or the activity is doing network calls on creation? See the threaddump logs. For your reference the last time the event queue was idle before your activity launch request was 1556450658437 and now the last time the queue went idle was: 1556450667375. If these numbers are the same your activity might be hogging the event queue.
at androidx.test.runner.MonitoringInstrumentation.startActivitySync(MonitoringInstrumentation.java:459)
at androidx.test.rule.ActivityTestRule.launchActivity(ActivityTestRule.java:358)
at
所以我需要两件事:
在TradersActivity
方法上启动@Before
。结果,我不需要每次测试该检查UI的活动。
在检查网络错误的测试(例如 http状态= 400 )上开始TradersActivity
如何在一个类TradersActivityTest
中做到这一点?
谢谢。