UI test deep linking using Espresso in Android
test dependencies
testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1' androidTestImplementation 'com.android.support.test.espresso:espresso-intents:3.0.1'
Deep linking test using ActivityTestRule and Espresso intented. The @Before
and @After
are required for each test. Initialize the intents before the test and release it afterwards. The intent is launched through the ActivityTestRule and verified by the Espresso intended
.
import android.support.test.espresso.intent.Intents import android.support.test.espresso.intent.Intents.intended import android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent import android.support.test.rule.ActivityTestRule import android.support.test.runner.AndroidJUnit4 import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import android.content.Intent import android.net.Uri @RunWith(AndroidJUnit4::class) class DeepLinkingTest { @Rule @JvmField val activityTestRule = ActivityTestRule(MainActivity::class.java) @Before fun setUp() { Intents.init() } @After fun tearDown() { Intents.release() } @Test fun should_launch_secondActivity_when_deepLinkingToActivityTwo() { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("myapp://example.com?screen=activitytwo")) activityTestRule.launchActivity(intent) intended(hasComponent(SecondActivity::class.java!!.getName())) } }
MainActivity.kt, the handleIntent()
function will redirect to the appropriate place according to the data found in the intent.
import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) handleIntent() } // adb shell am start -W -a android.intent.action.VIEW -d "myapp://example.com?screen=activitytwo" com.example.deeplinkinguitesting // adb shell am start -W -a android.intent.action.VIEW -d "http://www.example.com/myapp?screen=activitytwo" com.example.deeplinkinguitesting private fun handleIntent() { val data = intent.data if (data == null) return val screen = data.getQueryParameter("screen") if (screen == "activitytwo") { startActivity(Intent(this, SecondActivity::class.java)) } } }
SecondActivity.kt
import android.support.v7.app.AppCompatActivity import android.os.Bundle class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_two) } }
The intent-filters for deep linking in the MainActivity configuration in the manifest file.
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts