Last active
January 5, 2022 13:23
-
-
Save mh61503891/1d08575b3f16ddb99c2be5fd74c413ec to your computer and use it in GitHub Desktop.
Android Test with Jetpack Compose's IdlingResource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@LargeTest | |
@RunWith(AndroidJUnit4::class) | |
class ExampleScenarioTest { | |
@get:Rule | |
val composeTestRule = createAndroidComposeRule<MainActivity>() | |
private val mainIdlingResource = object : IdlingResource { | |
override var isIdleNow: Boolean = true | |
} | |
@Before | |
fun before() { | |
composeTestRule.activity.mainIdlingResource.onIdleStateChanged = { | |
mainIdlingResource.isIdleNow = it | |
} | |
composeTestRule.registerIdlingResource(mainIdlingResource) | |
} | |
@After | |
fun after() { | |
composeTestRule.unregisterIdlingResource(mainIdlingResource) | |
} | |
@Test | |
fun testExample() { | |
// do something | |
composeTestRule.waitForIdle() | |
// do something | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Masayuki Higashino | |
*/ | |
@HiltViewModel | |
class ExampleViewModel | |
@Inject constructor( | |
private val mainIdlingResource: MainIdlingResource, | |
) : ViewModel() { | |
fun sample() { | |
mainIdlingResource.isIdleNow = false | |
// do something | |
mainIdlingResource.isIdleNow = true | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Masayuki Higashino | |
*/ | |
@AndroidEntryPoint | |
class MainActivity : ComponentActivity() { | |
@Inject | |
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) | |
lateinit var mainIdlingResource: MainIdlingResource | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
MainScreen() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Masayuki Higashino | |
*/ | |
@Singleton | |
class MainIdlingResource @Inject constructor() { | |
var isIdleNow: Boolean = true | |
set(isIdleNow) { | |
field = isIdleNow | |
onIdleStateChanged(isIdleNow) | |
} | |
var onIdleStateChanged: (Boolean) -> Unit = {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment