To be honest, I do not think this is possible. I have the same problem. I fixed this with UIAutomator to click (in your case) the cancel button.
In my case, I had a login button, after which a map appeared. The application is never in standby mode after pressing the "Login" button or even only in MapFragment (a problem for espresso), so I had to use UIAutomator for the "Login" button and check if the map appears after logging in.
I inserted this depending on the application:
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
And in my LoginTest.kt file:
import androidx.test.uiautomator.* //your imports here @RunWith(AndroidJUnit4::class) @LargeTest class LoginTest { @Rule @JvmField //your rules here lateinit var mDevice:UiDevice @Before fun setUp() { //your setUp stuff mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()) } @Test fun checkLogin(){ onView(withId(R.id.loginBtn)).perform(click()) //goes to LoginFragment mDevice.findObject(UiSelector().text("LOGIN")).click() //clicks login button //this is where I had to use the UIAutomator because espresso would never be //idle after the login button mDevice.wait(Until.findObject(By.text("YOU HAVE LOGGED IN")),15000) //this waits until the object with the given text appears, max. wait time is 15 seconds //as espresso would still not be idle, I had to check if the login was successful //with (again) the help of UIAutomator } @After fun tearDown() { } }
hope this helps someone
source share