Я расширил класс InputMethodService
, чтобы создать собственный IME. Тем не менее, я изо всех сил пытаюсь написать действительные тестовые примеры Instrumentation, чтобы проверить поведение. Ранее 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 с действительным тестовым набором инструментов. .