Метод Android-тестирования, который возвращает идентификатор ресурса цвета из ссылки R.attr - PullRequest
1 голос
/ 22 мая 2019

Я впервые реализую AndroidInstrumentationTest с помощью Android Studio 3.2, пытаясь проверить, возвращает ли метод идентификатор ресурса цвета из атрибутов (R.attr и цвет, заданный в стилях) в зависимости от String, но вместо этого возвращаемый идентификатор ресурса всегда равен 0ожидаемого.

Код работает в моем приложении правильно, а цвет установлен следующим образом:

textView.setTextColor(fetchCorrectColor(myContext))

Проблема в fetchColor из тестов, возвращает 0

Другие ресурсы какmContext.getString () работает отлично

Тестовый класс аннотирован с помощью @RunWith (AndroidJunit4 :: class) и работает на эмуляции Android Pie (28) и устройстве

Я пробовал другой контекст с тем же результатом:

InstrumentationRegistry.getInstrumentation().targetContext
InstrumentationRegistry.getInstrumentation().context
ApplicationProvider.getApplicationContext()

Метод для проверки

fun getTextColor(status: String?, mContext: Context): Int{
    return when(status){
        "A", "B" ->{
            fetchCorrectColor(mContext)
        }
        "C", "D"->{
            fetchWarningColor(mContext)
        }
        else -> {
            fetchDisabledColor(mContext)
        }
    }
}

Методы для извлечения ресурса цвета, если из атрибутов

fun fetchCorrectColor(context: Context): Int{
    return fetchColor(context, R.attr.correct)
}

private fun fetchColor(context: Context, colorId: Int): Int{
    val typedValue = TypedValue()
    context.theme.resolveAttribute(colorId, typedValue, true)
    return typedValue.data
}

Тест

@Test fun getTextColor_isCorrect(){
    Assert.assertEquals(R.attr.correct, getTextColor("A", mContext))
    Assert.assertEquals(R.attr.correct, getTextColor("B", mContext))
    Assert.assertEquals(R.attr.warning, getTextColor("C", mContext))
    Assert.assertEquals(R.attr.warning, getTextColor("D", mContext))
    Assert.assertEquals(R.attr.disabled, getTextColor(null, mContext))
}

Thisэто ошибка, которую я получаю постоянно:

java.lang.AssertionError: expected:<2130968760> but was:<0>
at org.junit.Assert.fail(Assert.java:88)

1 Ответ

1 голос
/ 22 мая 2019

Атрибуты Theme осведомлены.Убедитесь, что context использует то же theme, что и ваше приложение:

appContext.setTheme(R.style.AppTheme)

Пример тестового кода, который разрешает атрибут R.attr.colorPrimary, доступный только в AppCompat theme:

@Test
fun testColorPrimary() {
    // Context of the app under test.
    val appContext = InstrumentationRegistry.getTargetContext()

    // actual R.color.colorPrimary value
    val actualPrimaryColor = appContext.getColor(R.color.colorPrimary)

    // R.attr.colorPrimary resolved with invalid theme
    val colorPrimary1 = TypedValue().also {
        appContext.theme.resolveAttribute(R.attr.colorPrimary, it, true)
    }.data

    // provided context has invalid theme so attribute resolution fails (returns 0)
    assertEquals(0, colorPrimary1)

    // be sure test context uses same theme as app
    appContext.setTheme(R.style.AppTheme)

    // R.attr.colorPrimary resolved from valid theme
    val colorPrimary2 = TypedValue().also {
        appContext.theme.resolveAttribute(R.attr.colorPrimary, it, true)
    }.data

    // valid theme returns proper color
    assertEquals(actualPrimaryColor, colorPrimary2)
}
...