Best practise for testing Android Deep Links navigation into activities

有些话、适合烂在心里 提交于 2020-05-17 07:02:47

问题


I have an activity for holding a fragment. I created this for being able to run Deep Link to the profile. Also I pass PROFILE_ID as a query parameter. So the whole deep link looks this: "tigranes://home/profile?profileId=3545664".

class ProfileActivity : BaseActivity() {

    companion object {
        @JvmStatic
        fun newInstance(context: Context, profileId: String): Intent {
            val intent = Intent(context, ProfileActivity::class.java)
            intent.putExtra(ProfileFragment.PROFILE_ID, profileId)
            return intent
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)

        val profileId: String = intent.getStringExtra(ProfileFragment.PROFILE_ID)
        val transaction = supportFragmentManager.beginTransaction()
        val fragment = ProfileFragment.newInstance(profileId)
        transaction.add(R.id.fragment_container, fragment)
        transaction.commit()
    }
}

So my question is what will be the best strategy for writing test checking if this deep link is opening ProfileActivity. I tried to use ActivityTestRule but I wasn't able to find a way for passing a parameters to it.


回答1:


Method newInstance() seems to be utter non-sense, because the Intent is being passed to the Activity; you should reconsider how that ProfileActivity is being constructed, because this is not how it works. getIntent() is all you need to get the Intent (as the method's name might suggest). Also @EpicPandaForce's suggestion should be taken into consideration, in order to avoid a mess. However, this wasn't the actual question (just telling, because you might claim "it doesn't work").


Testing an Activity with a deep-link Intent works alike this:

import android.content.Intent
import android.net.Uri
import androidx.test.ext.junit.rules.activityScenarioRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Rule
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class ProfileActivityTest {

    @get:Rule
    var testRule = activityScenarioRule<ProfileActivity>(
        Intent(Intent.ACTION_VIEW, Uri.parse(DEEP_LINK))
    )

    @Test
    ...

    companion object {
        val DEEP_LINK = "tigranes://home/profile?profileId=3545664"
    }
}

The activityScenarioRule depends on:

androidTestImplementation "androidx.test.ext:junit-ktx:1.1.1"

Please let me know if this works (this would require fixing the ProfileActivity in the first place).

Also make sure, that the intent-filter in the AndroidManifest.xml is setup properly.



来源:https://stackoverflow.com/questions/59921907/best-practise-for-testing-android-deep-links-navigation-into-activities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!