Android Espresso - 网络浏览器

use*_*539 10 android android-testing android-espresso

我有个问题

我想测试是否在按下按钮后使用espresso启动Web浏览器.问题是:是否有可能测试这样的事情?如果有的话,我会怎么做?

Wah*_*Haq 30

虽然这是一个老问题,但只是张贴在这里帮助其他人.我有同样的情况,我想验证一个特定的网址是否在浏览器中启动.我从这个链接得到了真正的帮助

我使用这段代码工作了:

    Intents.init();
    Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(EXPECTED_URL));
    intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
    onView(withId(R.id.someid)).perform(click());
    intended(expectedIntent);
    Intents.release();
Run Code Online (Sandbox Code Playgroud)

因此,它测试何时使用正确的URL打开浏览器,并且意图通过启用意图存根来实现魔术.使用它,我们可以拦截它,因此意图永远不会发送到系统.

  • 现在是 `androidTestImplementation 'androidx.test.espresso:espresso-intents:3.1.0'` https://developer.android.com/training/testing/espresso/intents (2认同)

IHe*_*oid 5

为方便起见,我建议一个完整的例子:


生产代码:

register_terms.text = Html.fromHtml(getString(R.string.register_terms,
        getString(R.string.privacy_policy_url),
        getString(R.string.register_terms_privacy_policy),
        getString(R.string.general_terms_and_conditions_url),
        getString(R.string.register_terms_general_terms_and_conditions)))
Run Code Online (Sandbox Code Playgroud)

字符串 XML:

<string name="register_terms">By registering you accept our &lt;a href=\"%1$s\">%2$s&lt;/a&gt; and the &lt;a href=\"%3$s\">%4$s&lt;/a&gt;.</string>
<string name="register_terms_privacy_policy">Privacy Policy</string>
<string name="register_terms_general_terms_and_conditions">General Terms and Conditions</string>

<string name="privacy_policy_url" translatable="false">https://www.privacypolicy.com</string>
<string name="general_terms_and_conditions_url" translatable="false">https://www.generraltermsandconditions.com</string>
Run Code Online (Sandbox Code Playgroud)

测试代码:

@Before
fun setUp() {
    Intents.init()
}

@After
fun tearDown() {
    Intents.release()
}

@Test
fun when_clickPrivacyLink_then_openPrivacyUrl() {
    val expected = allOf(IntentMatchers.hasAction(Intent.ACTION_VIEW), IntentMatchers.hasData(string(privacy_policy_url)))
    Intents.intending(expected).respondWith(Instrumentation.ActivityResult(0, null))

    onView(ViewMatchers.withId(R.id.register_terms))
            .perform(openLinkWithText(string(register_terms_privacy_policy)))

    Intents.intended(expected)
}
Run Code Online (Sandbox Code Playgroud)


Bol*_*oso 4

其实没有。Espresso 将允许您单击按钮,一旦浏览器启动,测试就会结束。您的替代方案是让您的类触发浏览器 Intent 模拟,以便您可以测试剩余的流程(如果有)。

看看这个答案:控制自动化测试结束时 - Espresso,我在其中描述了如何实现这一目标。