Commit fe182bc0 authored by Ahmed I. Khalil's avatar Ahmed I. Khalil
Browse files

Test helper for creating attached fragment

Closes #4120
parent 2c7d939f
Loading
Loading
Loading
Loading
+1 −0
Original line number Diff line number Diff line
@@ -36,6 +36,7 @@ dependencies {

    implementation Dependencies.androidx_test_junit
    implementation Dependencies.testing_mockito
    implementation Dependencies.androidx_fragment
    implementation (Dependencies.testing_robolectric) {
        exclude group: 'org.apache.maven'
    }
+32 −0
Original line number Diff line number Diff line
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package mozilla.components.support.test.robolectric

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import org.robolectric.Robolectric

/**
 * Set up an added [Fragment] to a [FragmentActivity] that has been initialized to a resumed state.
 *
 * @param fragmentTag the name that will be used to tag the fragment inside the [FragmentManager].
 * @param fragmentFactory a lambda function that returns a Fragment that will be added to the Activity.
 *
 * @return The same [Fragment] that was returned from [fragmentFactory] after it got added to the
 * Activity.
 */
inline fun <T : Fragment> createAddedTestFragment(fragmentTag: String = "test", fragmentFactory: () -> T): T {
    val activity = Robolectric.buildActivity(FragmentActivity::class.java)
            .create()
            .start()
            .resume()
            .get()

    return fragmentFactory().also {
        activity.supportFragmentManager.beginTransaction()
                .add(it, fragmentTag)
                .commitNow()
    }
}
+30 −0
Original line number Diff line number Diff line
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package mozilla.components.support.test.robolectric

import androidx.fragment.app.Fragment
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class FragmentsTest {

    @Test
    fun `setupFragment should add fragment correctly`() {
        val addedFragment = createAddedTestFragment { Fragment() }

        assertTrue(addedFragment.isAdded)
    }

    @Test
    fun `setupFragment should add fragment with correct tag`() {
        val fragment = createAddedTestFragment(fragmentTag = "aTag") { Fragment() }

        assertNotNull(fragment.fragmentManager?.findFragmentByTag("aTag"))
    }
}