I got to a project which uses Airbnb DeepLinkDispatch library. This part works fine, I'm able to run activities via URI + query params which parse fine too.
But when I tried using Espresso I got this issue - Intent does not contain Extra with URI and params.
The test I wrote:
class Test {
companion object {
#ClassRule
#JvmField
val rule = ActivityTestRule<MyActivity>(MyActivity::class.java, true, false)
}
#Before
fun setUp() {
val intent: Intent = MyActivity.createIntent(false)
rule.launchActivity(intent)
}
#Test
fun firstTest() {
onView(withId(R.id.switch))
.check(matches(isDisplayed()))
.perform(click())
Screengrab.screenshot("testtest")
}
}
I found out that onCreate in DeepLinkActivity is not called (the class which is annotated with #DeepLinkHandler(AppModule::class).
One way how to fix this could be adding missing EXTRA to the custom intent in setUp(), but this is something I don't want to do. It's a fragile solution and prone to future issues.
Any other ideas how to get espresso + deeplink running together?
Related
I am trying to test my lazy column in JetpackCompose and I keep getting this error:
[Compose-Espresso link] to become idle timed out
I tried using composeTestRule.waitforIdle() but it doesn't work. What am I missing here?
#HiltAndroidTest
class MainTest {
#get:Rule(order = 1)
var hiltTestRule = HiltAndroidRule(this)
#get:Rule(order = 2)
var composeTestRule = createAndroidComposeRule<MainActivity>()
private val context = InstrumentationRegistry.getInstrumentation().context
#Before
fun setup() {
hiltTestRule.inject()
composeTestRule.setContent {
HomePage(
context = context,
viewModel = composeTestRule.activity.viewModels<MarvelViewModel>().value,
onClick = {}
)
}
composeTestRule.onRoot().printToLog("currentLabelExists")
}
#Test
fun isResultDisplayedOnLazyColumn() {
composeTestRule.waitForIdle()
composeTestRule.onNode(hasImeAction(ImeAction.Done)).performTextInput("iron man")
composeTestRule.onNode(hasImeAction(ImeAction.Done)).performImeAction()
composeTestRule.onNodeWithTag(TAG_LAZY_COLUMN, useUnmergedTree = true).assertIsDisplayed()
I've got this issue too. The root cause was having my composeview GONE. It seems ComposeTestRule IdlingResource don't like then you call setContent on a Gone ComposeView
After several hours of trials and experimentation, l found a way to fix this issue in a recent project. I would advise to try the following:
Update compose version to 1.2.0-Alpha06 as Skav mentioned. For me that implies bumping my kotlin version to 1.7.0 which my team is not ready for.
So I did some digging around the IdlingRegistry and found that unregistering Espresso-Compose Idling resource at the right spot in the test fixed the issue and my UI test passed afterwards.
IdlingRegistry.getInstance().resources.forEach {
Timber.e("resource ${it.name} idleNow: ${it.isIdleNow}")
if (it.name == "Compose-Espresso link") {
IdlingRegistry.getInstance().unregister(it)
}
}
It is important to note that unregistering Espresso-Compose too early can make your compose ui to fail to display. In my case, l ran this code after the UI is ready before testing for specific UI functionalities.
Building on top of the answer from #leeCoder, I've discovered that upgrading to Compose 1.2.0 (alpha no longer necessary) fixed my problem and there was no need to unregister anything (which was the part that made me the most nervous about his answer).
I am using Espresso with Kotlin for the UI test automation. I am trying to find a proper way to restart the app during the test and start it again, so the test scenario is the following:
start the app, go to login page
force close the app and open it again (basically restart it)
check some stuff etc
The way our UI tests are organized:
there is a test class where I have rules
val intent = Intent(ApplicationProvider.getApplicationContext(), MainActivity::class.java)
.putExtra(UI_TEST_INTENT, true)
#get:Rule
val rule = ActivityScenarioRule<MainActivity>(intent)
there Before/After functions and tests functions in this class
What I want is to have generic restartApp function in separated class, let's say TestUtils and to be able to call it at any point of time, when is needed.
So far I didn't find a solution. There are some similar questions on stackoverflow, but I am not sure I understand how to work with the answers I found, like this:
with(activityRule) {
finishActivity()
launchActivity(null)
}
Since ActivityTestRule is deprecated and documentation asking to use ActivityScenarioRule, I tried this:
#get:Rule
val rule = ActivityScenarioRule<MainActivity>(intent)
private fun restart() {
rule.scenario.close()
rule.scenario.recreate()
}
but it gets java.lang.NullPointerException
another option is
private fun restart() {
pressBackUnconditionally()
Intents.release()
ActivityScenario.launch<MainActivity>(intent)
}
it works, app restarts but I can not interact with the app anymore, because for some reason there are two intents running now
Would be great to get an answer I can work with (I am quite new to Espresso)
Cheers
The solution is found:
private fun restart() {
Intents.release()
rule.scenario.close()
Intents.init()
ActivityScenario.launch<MainActivity>(intent)
}
Seems like the author's answer has some excess code. The following is enough
activityScenarioRule.scenario.close()
ActivityScenario.launch(YourActivity::class.java, null)
I'm currently adding a view developed using Flutter to an existing Android app. I have been following the tutorials found in the Flutter website and decided to used a cached engine in order to minimize the delay that users may experience when navigating to the Flutter portion of the app. In order to do so, you must launch your Flutter activity like
startActivity(
FlutterActivity
.withCachedEngine("my_engine_id")
.build(this) // this is a Context
)
After a while I need to wirte a method channel to communicate from the Flutter portion of the app back to the Android host app, so I followed the instructions found in another of Flutter's tutorials, where it is shown that the activity that implements the channel must extend FlutterActivity.
So my problem is that I'm not sure how to initialize this activity using a cached engine, since I obviously can't use FlutterActivity.withCachedEngine anymore. Has anyone solved this already?
After looking at FlutterActivity documentation I found the provideFlutterEngine method. The doc description clearly states that:
This hook is where a cached FlutterEngine should be provided, if a cached FlutterEngine is desired.
So the final implementation of my class looks like this now
class MyActivity : FlutterActivity() {
override fun provideFlutterEngine(context: Context): FlutterEngine? =
FlutterEngineCache.getInstance().get(FlutterConstants.ENGINE_ID)
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "my-channel")
.setMethodCallHandler { call, result ->
if (call.method == "my-method") {
myMethod()
result.success(null)
} else {
result.notImplemented()
}
}
}
private fun myMethod() {
// Do native stuff
}
}
And I simply start it writing startActivity(Intent(this, MyActivity::class.java))
I have a testsuite which has mutiple testcases in a class
every test case is isolated
So when i execute the testsuite class i want to restart the app for every testcase
How do i relaunch application from start for every individual test case in Espresso
Thanks in advance
#Test
public void testcase1() {
//from first screen
}
#Test
public void testcase2() {
//from first screen
}
There is another stack overflow answer that seems to answer this question. If you were looking to do that in Kotlin though I converted the answer to relaunch multiple times for different tests.
#RunWith(AndroidJUnit4::class)
class ExampleEspressoTest {
#get:Rule
val rule = ActivityTestRule(
activityClass = MainActivity::class.java,
initialTouchMode = false,
launchActivity = false) //set to false to customize intent
#Test
fun testCustomIntent() {
val intent = Intent().apply {
putExtra("your_key", "your_value")
}
rule.launchActivity(intent)
//continue with your test
}
}
If you need to start a method/test and when it's finished clear data and start the next one, you should use commands.
Look at this documentation: https://developer.android.com/studio/test/command-line
I'm using this command:
./gradlew testVariantNameUnitTest --tests *.sampleTestMethod
There could be several ways to do this but we wanted a way that works both locally as well as google fire base test lab, so ended up with using configuration in build.gradle file under default config.
defaultConfig{
testInstrumentationRunnerArguments clearPackageData: 'true'
}
Reference: https://developer.android.com/training/testing/junit-runner#ato-gradle
Also you use these runner arguments for configuring different tests you wanted run based on build variants or other config options, look at my post if you want more detail.
Here is the stub of the code.
Click data item on ListView . Works as designed and opens Chrome Custom Tab :
onData(anything()).inAdapterView(withId(R.id.listView))
.atPosition(0).perform(click());
Pause(5000);
Espresso.pressBack();
Cannot seem to evaluate anything in the tab or even hit device back button.
Getting this error
Error : android.support.test.espresso.NoActivityResumedException: No
activities in stage RESUMED.
Did you forget to launch the activity. (test.getActivity() or similar)?
You can use UIAutomator (https://developer.android.com/training/testing/ui-automator.html). You can actually use both Espresso and UIAutomator at the same time. See the accepted answer on the following post for more information:
How to access elements on external website using Espresso
You can prevent opening Custom Tabs and then just assert whether the intent you are launching is correct:
fun stubWebView(uri: String) {
Intents.intending(allOf(IntentMatchers.hasAction(Intent.ACTION_VIEW), IntentMatchers.hasData(uri)))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null))
}
fun isNavigatedToWebView(uri: String) {
Intents.intended(allOf(IntentMatchers.hasAction(Intent.ACTION_VIEW), IntentMatchers.hasData(uri)))
}
This way you can avoid Espresso.pressBack() in your test.
Note that since these are using Espresso Intents, you need to either use IntentsTestRule or wrap these with Intents.init and release like this
fun intents(func: () -> Unit) {
Intents.init()
try {
func()
} finally {
Intents.release()
}
}
intents {
stubWebView(uri = "https://www.example.com")
doSomethingSuchAsClickingAButton()
isNavigatedToWebView(uri = "https://www.example.com")
}
A suggestion for improved readability following Mustafa answer:
intents{
Intents.intended(
CoreMatchers.allOf(
IntentMatchers.hasAction(Intent.ACTION_VIEW),
IntentMatchers.hasPackage("com.android.chrome")
)
)
}