InputMethodService的Instrumentation测试用例

时间:2018-05-14 04:50:09

标签: android android-input-method android-service-binding android-instrumentation servicetestcase

我已经扩展了InputMethodService类来创建我的自定义IME。但是,我正在努力编写有效的Instrumentation测试用例来验证行为。以前Service可以使用ServiceTestCase<YourServiceClass>进行测试。但它似乎已被弃用,新格式看起来像this。现在在给定的指导方针中,我正在努力解决这个片段:

CustomKeyboardService service =
            ((CustomKeyboardService.LocalBinder) binder).getService();

由于我正在扩展InputMethodService,因此它已经抽象了IBinder,如何获取LocalBinder来运行此代码段?目前,此代码段引发以下异常:

  

java.lang.ClassCastException:   android.inputmethodservice.IInputMethodWrapper无法强制转换为   com.osrc.zdar.customkeyboard.CustomKeyboardService $ LocalBinder

扩展类看起来像:

public class CustomKeyboardService extends InputMethodService {

    // Some keyboard related stuff

    public class LocalBinder extends Binder {

        public CustomKeyboardService getService() {
            // Return this instance of LocalService so clients can call public methods.
            return CustomKeyboardService.this;
        }
    }

    // Some keyboard related stuff

}

如何扩展自定义类,CustomKeyboardService service = ((CustomKeyboardService.LocalBinder) binder).getService();不会返回错误?

这是我的测试用例代码:

@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest2 {
    @Rule
    public final ServiceTestRule mServiceRule = new ServiceTestRule();

    @Test
    public void testWithBoundService() throws TimeoutException {
        // Create the service Intent.
        Intent serviceIntent =
                new Intent(InstrumentationRegistry.getTargetContext(), CustomKeyboardService.class);

        // Bind the service and grab a reference to the binder.
        IBinder binder = mServiceRule.bindService(serviceIntent);

        // Get the reference to the service, or you can call public methods on the binder directly.
        //  This Line throws the error
        CustomKeyboardService service =
                ((CustomKeyboardService.LocalBinder) binder).getService();
    }

}

您还可以在Github上查看OimeKeyboard以获取完整的源代码,并提交带有效的仪器测试用例的PR。

1 个答案:

答案 0 :(得分:0)

我发生了同样的问题,请检查以下链接的解决方案。
通过链接更新了代码段:

console.nextInt()

来自:https://github.com/sealor/prototype-Android-Espresso-Keyboard-Testing