Android :java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission

前端 未结 9 1455
感动是毒
感动是毒 2020-12-01 11:48

Hi there I am new to Android Junit testing:

I have written some test code in MainActivityFunctionalTest.java file

MainActivityFunctionalTest.java:

         


        
9条回答
  •  爱一瞬间的悲伤
    2020-12-01 12:45

    I had the same problem, and my code was something like this (for a normal login activity):

        onView(withId(R.id.username))
                .perform(new TypeTextAction("test_user"));
        onView(withId(R.id.password))
                .perform(new TypeTextAction("test123"));
        onView(withId(R.id.login)).perform(click());
    

    The last line was crashing with SecurityException. Turned out after the last text typing, the keyboard was left open, hence the next click was considered on a different application.

    To fix this, I simply had to close the keyboard after typing. I also had to add some sleep to make sure the keyboard is closed, otherwise the test would break every now and then. So the final code looked like this:

        onView(withId(R.id.username))
                .perform(new TypeTextAction("test_user"));
        onView(withId(R.id.password))
                .perform(new TypeTextAction("test123")).perform(closeSoftKeyboard());
        Thread.sleep(250);
        onView(withId(R.id.login)).perform(click());
    

    This worked just fine.

提交回复
热议问题