Hilt Test - Fragment trouble: this needs special treatment, starting a new stove, counterfeiting process, making empty birth, just for a Fragment.

Posted by langer on Tue, 08 Mar 2022 05:33:34 +0100

πŸšͺ 1. Fragment report Gradle

Gradle - Module:

    def fragment_version = "1.3.1"
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"

πŸ˜“: You see, this is not Android test or test, but debug. We don't have it!
πŸ€—: haven't you? You have to make it yourself.

πŸ”¨ 2. Create the debug folder.

Select Project View, app/src, New Folder, Java Folder

Select debug and finish.
Now you can add package. Type in your own package name.


Super fast, no need to build one by one.

Take selling goods as an example and add a shoppinglist package:

β­• 3. Short activity

πŸ˜‘: Borrow money or stock?
πŸ™€: Lao Cao, I don't know. I never borrow money unless I buy a house. My wife is urging me when to buy a house. Isn't this putting the cart before the horse? I haven't found a job yet. I'll review how to test and debug here.

Fragment test steps are:

  1. Create a short activity.
  2. Open the fragment in the short activity to test.

If you have a plan, let it go!
Counterfeiting activity (nothing): HiltTestActivity()

@AndroidEntryPoint
class HiltTestActivity : AppCompatActivity()

Really empty.

πŸ“œ 4. Debug Manifest

If there are activities, of course, there is Manifest. Copy it from the original.
Change the activity name to HiltTestActivity.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.homan.huang.pixbaysample">

    <application>

        <activity
            android:name=".HiltTestActivity"
            android:exported="false" />

    </application>

</manifest>

This Manifest is very useful. If you have any special requirements, you can plug it in here and go through the back door. For example, MockWebserver, Android will warn you that using localhost is illegal. You can't use it. You can open the door here.

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <application
        android:networkSecurityConfig="@xml/network_security_config"
        >
        <activity
            android:name=".HiltTestActivity"
            android:exported="false" />

    </application>
</manifest>

You see, I added Internet terms to XML.

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">localhost</domain>
    </domain-config>
</network-security-config>

Note: I want to use localhost. With this, you can use the equation of MockWebserver.

πŸ‘¨‍πŸ”§ 5. HiltUtil tools

  • βž• debug_helper package
  • βž• helper.kt
const val THEME_EXTRAS_BUNDLE_KEY = "theme extras bundle key"
  • βž• HiltUtil.kt
    Equation: lauchFragmentInHilt()
const val THEME_EXTRAS_BUNDLE_KEY = "androidx.fragment.app.testing.FragmentScenario.EmptyFragmentActivity.THEME_EXTRAS_BUNDLE_KEY"

@ExperimentalCoroutinesApi
inline fun <reified T : Fragment> launchFragmentInHiltContainer(
    fragmentArgs: Bundle? = null,
    themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme,
    fragmentFactory: FragmentFactory? = null,
    crossinline action: T.() -> Unit = {}
) {
    val mainActivityIntent = Intent.makeMainActivity(
        ComponentName(
            ApplicationProvider.getApplicationContext(),
            HiltTestActivity::class.java
        )
    ).putExtra(THEME_EXTRAS_BUNDLE_KEY, themeResId)
    ActivityScenario.launch<HiltTestActivity>(mainActivityIntent).onActivity { activity ->
        fragmentFactory?.let {
            activity.supportFragmentManager.fragmentFactory = it
        }
        val fragment = activity.supportFragmentManager.fragmentFactory.instantiate(
            Preconditions.checkNotNull(T::class.java.classLoader),
            T::class.java.name
        )
        fragment.arguments = fragmentArgs
        activity.supportFragmentManager.beginTransaction()
            .add(android.R.id.content, fragment, "")
            .commitNow()
        (fragment as T).action()
    }
}

This is a little different from the original version. The original version has to use the parameter of FragmentActivity. In fact, what do you use is not the same? The_ EXTRAS_ BUNDLE_ Key, you can change it at will. After that, with this, you can transfer the Fragment with the Hilt installed.

🐀 6. Actual measurement

Or take the shopping daotest to play. Everyone likes online shopping, don't they? Actually, it was the Hilt Test in the previous article.

@ExperimentalCoroutinesApi
@SmallTest
@HiltAndroidTest
class ShoppingDaoTest {

    // Hit rule
    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    // One time task rule
    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @Inject
    @Named("memory.db")
    lateinit var database: ShoppingItemDatabase

    private lateinit var dao: ShoppingDao

    @Before
    fun setup() {
        hiltRule.inject()
        dao = database.shoppingDao()
    }

    @After
    fun teardown() {
        database.close()
    }

Add a Fragment to see:

@Test
fun testLaunchFragment() {
    launchFragmentInHiltContainer<Yours Fragment> {
    }
}

It doesn't matter if it's empty. It can be measured now. πŸƒ Run away!
...
🐧: Pass,Yes !
πŸ™Š: Play off, empty also risk Error! Is there a mistake?

java.lang.RuntimeException: Unable to resolve 
activity for: Intent {
 act=android.intent.action.MAIN 
 cat=[android.intent.category.LAUNCHER] 
 cmp=com.homan.huang.pixbaysample/.HiltTestActivity (has extras) }

When you see this, you will know that the Android manifest was thrown in the wrong place. Many times, people have the illusion that they see this as a pair:

Let's just pull over my English version. I'm too lazy to change it.
In fact, it's almost. When you open debug, you can see:

So, Android manifest

Move up.

No more running.

πŸ‘‹ 7. English version

Old tune, help me, πŸ‘‹ Clap your hands. You're great, too.
To Make Fragment Test Under Hilt Installed

Topics: Android Android Studio kotlin Testing