Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test InputMethodService

I have a basic implementation of the Android InputMethodService which I am trying to write unit tests for. My application does not have any Activites, just the implementation of InputMethodService.

So far I have a basic implementation of a ServiceTestCase which is working great:

SoftKeyboardTest.java

    public class SoftKeyboardTest extends ServiceTestCase<SoftKeyboard> {

        @Override
        protected void setUp() throws Exception {
            super.setUp();
            bindService(new Intent(this.getContext(), SoftKeyboard.class));
        }

        public void testShowKeyboard() {
            this.getService().ShowKeyboard();
            assertTrue(this.getService().GetKeyboardIsVisible());
        }

        public void testInsertText() {
            String text = "Hello, world";
            this.getService().InsertText(text);
            assertEquals(this.getService().ReadText(text.length()), text);
        }
}

However, I would like to test some of the functionality which inserts text into the currently focused EditText using getCurrentInputConnection():

SoftKeyboard.java

public void InsertText(String sentence) {
    getCurrentInputConnection().commitText(sentence, 1);
}

public void ReadText(int chars) {
    getCurrentInputConnection().getTextBeforeCursor(chars, 0);
}

Obviously in this case I get a NullPointerException due to there not actually being any focused EditText.

How can I get my test application to launch my service, somehow focus on an EditText, then launch my test cases so that I can properly test my service methods?

like image 953
CodingIntrigue Avatar asked Jun 24 '13 14:06

CodingIntrigue


1 Answers

If you're doing unit testing on the input method, I'd test it at a level low enough it doesn't need to have an InputConnection. If you're doing integration/acceptance level testing, I'd just write an app with an edit text field, and drive input/output through there.

But really, having done this for 2 years- tests at that level will be almost useless. Your problems won't be from the default edit text implementation- it will be from the thousands of apps that subclass EditText or create their own EditText classes that behave subtly different. You can't automated test for that, and you'll spend man years fixing the bugs on them.

like image 106
Gabe Sechan Avatar answered Oct 10 '22 14:10

Gabe Sechan