超时未找到活动。您是否忘了通过调用getActivity()或startActivitySync或类似方法来启动活动?

时间:2019-05-01 10:57:49

标签: android-espresso ui-testing mockwebserver

在android应用中,我有2个editText和一个按钮。
我要编写测试,以确保在填写这两个editText并单击按钮时,我想模拟超时。

这是我的意式浓缩咖啡的测试:

import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit

@RunWith(AndroidJUnit4::class)
class AddTraderActivityNetworkTest {
    private val context = InstrumentationRegistry.getInstrumentation().getContext()
    private lateinit var mockServer: MockWebServer

    @Rule
    @JvmField
    var addTraderIntentTestRule: IntentsTestRule<AddTraderActivity> = IntentsTestRule(AddTraderActivity::class.java)

    @Before
    fun setup() {
        mockServer = MockWebServer()
        mockServer.start(8081)
    }

    @Test
    fun buttonStart_click_timeOut_showToast() {
        mockServer.enqueue(MockResponse()
                .setResponseCode(200)
                .throttleBody(1024, 1, TimeUnit.SECONDS))

        onView(withId(R.id.baseTextInputEditText))
                .perform(typeText(BASE_TEST))
        onView(withId(R.id.quoteTextInputEditText))
                .perform(typeText(QUOTE_TEST))
        onView(withId(R.id.startButton))
                .perform(click())
        onView(withText(R.string.service_unavailable)).inRoot(ToastMatcher())
                .check(matches(isDisplayed()))
    }

    @After
    @Throws
    fun tearDown() {
        // We're done with tests, shut it down
        mockServer.shutdown()
    }
}

此处是自定义匹配项:

class ToastMatcher : TypeSafeMatcher<Root>() {

    override fun describeTo(description: Description) {
        description.appendText("is toast")
    }

    override fun matchesSafely(root: Root): Boolean {
        val type = root.getWindowLayoutParams().get().type
        if (type == WindowManager.LayoutParams.TYPE_TOAST) {


              val windowToken = root.getDecorView().getWindowToken()
                val appToken = root.getDecorView().getApplicationWindowToken()
                if (windowToken === appToken) {
                    return true
                }
            }
            return false
        }
    }

但是当我开始测试时 buttonStart_click_timeOut_showToast失败,并显示下一条错误消息:


    java.lang.RuntimeException: No activities found. Did you forget to launch the activity by calling getActivity() or startActivitySync or similar?
    at androidx.test.espresso.base.RootViewPicker.waitForAtLeastOneActivityToBeResumed(RootViewPicker.java:169)
    at androidx.test.espresso.base.RootViewPicker.get(RootViewPic

0 个答案:

没有答案