我有一个问题
我想测试按钮点击后是否使用espresso启动Web浏览器。 问题是:是否有可能测试这样的事情? 如果有的话,我会怎么做?
答案 0 :(得分:27)
虽然这是一个老问题,但只是张贴在这里帮助其他人。我有同样的情况,我想验证一个特定的URL是否在浏览器中启动。我从link
获得了真正的帮助我使用这段代码完成了它的工作:
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();
因此,它测试何时使用正确的URL打开浏览器,intending()通过启用意图存根来实现这一点。使用它,我们可以拦截它,因此永远不会将意图发送到系统。
答案 1 :(得分:3)
其实没有。 Espresso将允许您单击按钮,一旦浏览器启动,测试将结束。您可以选择让您的类触发浏览器Intent模拟,以便您可以测试剩余的流量(如果有的话)。
看看这个答案:Controlling when an automation test ends - Espresso,我在那里描述你如何实现这个目标。
答案 2 :(得分:3)
为方便起见,我建议一个完整的例子:
生产代码:
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)))
字符串XML:
<string name="register_terms">By registering you accept our <a href=\"%1$s\">%2$s</a> and the <a href=\"%3$s\">%4$s</a>.</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>
测试代码:
@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)
}