Контрольно-измерительные приборы для InputMethodService
Я продлил InputMethodService
класс для создания моего собственного IME. Тем не менее, я изо всех сил пытаюсь написать действительные контрольные примеры инструментов для проверки поведения. Ранее Service
, может быть проверено с помощью ServiceTestCase<YourServiceClass>
, Но, похоже, это устарело, и новый формат выглядит следующим образом. Теперь в данном руководстве я борюсь с этим фрагментом:
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();
}
}
Вы также можете проверить OimeKeyboard на Github для получения полного исходного кода и отправить PR с действительным тестовым набором инструментов.
1 ответ
Та же проблема произошла со мной, пожалуйста, проверьте решение по ссылке ниже.
Обновлены фрагменты кода по ссылке:
@Rule
public final ServiceTestRule mServiceRule = new ServiceTestRule();
private MyKeyboard retrieveMyKeyboardInstance(IBinder binder) {
try {
Class wrapperClass = Class.forName("android.inputmethodservice.IInputMethodWrapper");
Field mTargetField = wrapperClass.getDeclaredField("mTarget");
mTargetField.setAccessible(true);
WeakReference<MyKeyboard> weakReference = (WeakReference<MyKeyboard>) mTargetField.get(binder);
return weakReference.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void validateEditTextWithKeyboardInput() throws TimeoutException {
...
Intent serviceIntent = new Intent(InstrumentationRegistry.getTargetContext(), MyKeyboard.class);
IBinder binder = mServiceRule.bindService(serviceIntent);
MyKeyboard keyboard = retrieveMyKeyboardInstance(binder);
...
}
От: https://github.com/sealor/prototype-Android-Espresso-Keyboard-Testing