为扩展设计库布局的自定义布局编写Android测试



我正在尝试测试自定义布局,该布局从设计库中扩展了TextInputLayout。当我运行测试时,我会得到错误

java.lang.illegalargumentException:您需要与设计库一起使用theme.AppCompat主题(或后代)。 在Android.support.design.widget.themeutils.checkappcompattheme(eyutils.java:33) 在android.support.design.widget.textinputlayout。(textInputlayout.java:192) at android.support.design.widget.textinputlayout。(textInputlayout.java:185) 在Android.support.design.widget.textinputlayout。(textInputlayout.java:181)

我正在使用InstrumentationRegistry.getTargetContext()提供的上下文来实例化自定义布局。我该如何解决?

在上下文对象上调用 setTheme()在使用appcompat主题的上下文对象上,然后使用它实例化自定义布局,如下示例测试方法所示。

@Test
public void testCustomLayout() {
    Context context = InstrumentationRegistry.getContext();
    context.setTheme(R.style.Theme_AppCompat);
    CustomLayout textInputEditText = new CustomLayout(context);
    assertNotNull(textInputEditText);
}

最新更新