我有一个基本的 Android InputMethodService 实现,我正在尝试编写单元测试。我的应用程序没有任何活动,只有 InputMethodService 的实现。
到目前为止,我有一个基本的 ServiceTestCase 实现,运行得很好:
然而,我想测试一些将文本插入当前焦点EditText的功能,使用getCurrentInputConnection():
显然,在这种情况下,我会因为实际上没有任何焦点在的EditText而得到一个NullPointerException。
我该如何让我的测试应用程序启动我的服务,以某种方式聚焦于EditText,然后启动我的测试用例,以便我可以正确地测试我的服务方法?
到目前为止,我有一个基本的 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);
}
}
然而,我想测试一些将文本插入当前焦点EditText的功能,使用getCurrentInputConnection():
SoftKeyboard.java
public void InsertText(String sentence) {
getCurrentInputConnection().commitText(sentence, 1);
}
public void ReadText(int chars) {
getCurrentInputConnection().getTextBeforeCursor(chars, 0);
}
显然,在这种情况下,我会因为实际上没有任何焦点在的EditText而得到一个NullPointerException。
我该如何让我的测试应用程序启动我的服务,以某种方式聚焦于EditText,然后启动我的测试用例,以便我可以正确地测试我的服务方法?