1515 */
1616
1717package com.android.samples.webviewdemo
18-
19- import androidx.test.platform.app.InstrumentationRegistry
18+ import androidx.test.espresso.web.assertion.WebViewAssertions.webMatches
19+ import androidx.test.espresso.web.sugar.Web.onWebView
20+ import androidx.test.espresso.web.webdriver.DriverAtoms.findElement
21+ import androidx.test.espresso.web.webdriver.DriverAtoms.getText
22+ import androidx.test.espresso.web.webdriver.DriverAtoms.webClick
23+ import androidx.test.espresso.web.webdriver.Locator
2024import androidx.test.ext.junit.runners.AndroidJUnit4
21-
25+ import androidx.test.rule.ActivityTestRule
26+ import org.hamcrest.CoreMatchers.containsString
27+ import org.junit.Rule
2228import org.junit.Test
2329import org.junit.runner.RunWith
2430
25- import org.junit.Assert.*
2631
2732/* *
2833 * Instrumented test, which will execute on an Android device.
@@ -31,10 +36,53 @@ import org.junit.Assert.*
3136 */
3237@RunWith(AndroidJUnit4 ::class )
3338class ExampleInstrumentedTest {
39+
40+ @Rule @JvmField
41+ val activityRule = ActivityTestRule (MainActivity ::class .java)
42+
43+ fun afterActivityLaunched () {
44+ // Technically we do not need to do this - MainActivity has javascript turned on.
45+ // Other WebViews in your app may have javascript turned off, however since the only way
46+ // to automate WebViews is through javascript, it must be enabled.
47+ onWebView().forceJavascriptEnabled()
48+ }
49+
50+
51+ @Test
52+ fun webViewTest () {
53+
54+ activityRule.getActivity()
55+
56+
57+ onWebView()
58+ .withElement(findElement(Locator .ID , " title" ))
59+ .check(webMatches(getText(), containsString(" New York" )))
60+ // .perform(webClick())
61+ // .withElement(findElement(Locator.TAG_NAME, "h1"))
62+ // .check(webMatches(getText(), containsString("Apple")))
63+
64+
65+ }
66+
67+
68+ // Test for calling postMessage
3469 @Test
35- fun useAppContext () {
36- // Context of the app under test.
37- val appContext = InstrumentationRegistry .getInstrumentation().targetContext
38- assertEquals(" com.android.samples.webviewdemo" , appContext.packageName)
70+ fun callPostMessage () {
71+ onWebView()
72+ // Click on the share button
73+ .withElement(findElement(Locator .ID , " share" )) // similar to onView(withId(...))
74+ .perform(webClick()) // Similar to perform(click())
75+
76+ // check that an intent was created
77+
78+ // verify that the data send to post message looks correct
79+
80+ // .get()
81+ // .value
82+
83+
84+ // Similar to check(matches(...))
85+ // .check(webMatches(executeScript)
86+
3987 }
4088}
0 commit comments