【发布时间】:2013-06-24 14:40:55
【问题描述】:
我有一个 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);
}
显然,在这种情况下,由于实际上没有任何聚焦的 EditText,我得到了 NullPointerException。
如何让我的测试应用程序启动我的服务,以某种方式关注 EditText,然后启动我的测试用例,以便我可以正确地测试我的服务方法?
【问题讨论】:
-
也许正如他们在此线程中所建议的那样? (使用 requestFocus())stackoverflow.com/questions/8080579/…
-
我愿意,但我没有可用的 EditText。我的应用程序只是一个没有前端 UI 的服务。我正在寻找的是某个全局控件上的 requestFocus() - 也许通过 UI 自动化?
-
好的,所以我在寻找 android testUtil 类时搜索了一下,我在 GitHub 上找到了一个项目,但他们使用了一些自定义导入,我不确定它是否适合您的项目。但这里是:github.com/japgolly/android-test-utils/tree/master/src/main/…
标签: java android junit android-service android-testing