如何测试InputMethodService

时间:2013-06-24 14:40:56

标签: java android junit android-service android-testing

我有Android InputMethodService的基本实现,我正在尝试编写单元测试。我的应用程序没有任何Activites,只是InputMethodService的实现。

到目前为止,我有一个ServiceTestCase的基本实现,它运行得很好:

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);
        }
}

但是,我想测试一些使用getCurrentInputConnection()将文本插入当前焦点的EditText的功能:

SoftKeyboard.java

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

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

显然在这种情况下我得到一个NullPointerException,因为实际上没有任何聚焦的EditText。

如何让我的测试应用程序启动我的服务,以某种方式专注于EditText,然后启动我的测试用例以便我可以正确测试我的服务方法?

1 个答案:

答案 0 :(得分:2)

如果你正在对输入法进行单元测试,我会在足够低的水平上测试它,不需要输入InputConnection。如果您正在进行集成/验收级别测试,我只需编写一个带有编辑文本字段的应用程序,并通过那里驱动输入/输出。

但实际上,这样做了两年 - 在那个级别的测试几乎是无用的。您的问题不会来自默认的编辑文本实现 - 它将来自成千上万的子类EditText的应用程序或创建自己的EditText类,其行为略有不同。你不能自动进行测试,你会花费数年的时间来修复它们上的错误。

相关问题