Инструментальные тестовые случаи для InputMethodService

Я расширил класс 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 с действительным тестовым набором инструментов. .




Ответы (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

person Hitchhiker    schedule 13.11.2018