Shopify / android-testify

Add screenshots to your Android tests
https://testify.dev
MIT License
231 stars 23 forks source link

Question: Is it possible to run Testify alongside Dagger Hilt? #257

Closed nicolascapracredera closed 2 years ago

nicolascapracredera commented 2 years ago

Apologies for posting both here and StackOverflow but it's been quite a while with no response there.

My question is, is Testify compatible with Dagger Hilt? I have had trouble creating the test rule and running it when my project uses Hilt. Thank you for any guidance!

Original StackOverflow question: https://stackoverflow.com/questions/69802966/how-can-i-run-android-testify-tests-with-dagger-hilt

DanielJette commented 2 years ago

Hi @nicolascapracredera I'm sorry, I missed the Stack Overflow post. Thanks for opening the issue here.

I don't have any first-hand experience with Hilt and Testify, but I do have some experience with mixing multiple test Rule instances together. The issue there is that each rule assumes that it's going to be the only test rule running in a given test class. So, declaring multiple Rule instances can have them compete with one another and leave them in a state where they just fail immediately.

In order to get the rules to work together, you may need to use a ruleChain.

https://junit.org/junit4/javadoc/4.12/org/junit/rules/RuleChain.html

This article on developer.android.com demonstrates a couple of techniques for dealing with multiple TestRule objects in your tests: https://developer.android.com/training/dependency-injection/hilt-testing#multiple-testrules

nicolascapracredera commented 2 years ago

Thanks @DanielJette! I've accepted your answer on StackOverflow as well, but wanted to note this is what my rules ended up looking like, in case others come along. I was not able to get RuleChain.outerRule().around() to work, so mine was:

@get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)

@get:Rule(order = 1)
var screenshotRule = ScreenshotRule(MyActivity::class.java)

and as a side note, I had issues because my activity requires an intent extra, so the final code is:

@get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)

@get:Rule(order = 1)
var screenshotRule = ScreenshotRule(MyActivity::class.java, launchActivity = false)

@ScreenshotInstrumentation
@Test
fun default() {
    screenshotRule.addIntentExtras { it.putParcelable(MyActivity.OBJECT_KEY, testObject) }.assertSame()
}