Android Studio 3.3。浓缩咖啡在Kotlin上的测试。
这是我的xml
<TextView
android:id="@+id/toolbaTitleTextView"
style="@style/textViewOneLine"
android:layout_width="0dp"
android:layout_height="0dp"
android:textSize="@dimen/tool_bar_text_size"
/>
<dimen name="tool_bar_text_size">13sp</dimen>
此处测试检查文字大小:
@Test
fun toolbar_title_textSize() {
onView(withId(R.id.toolbaTitleTextView))
.check(matches(withFontSizeResId(R.dimen.tool_bar_text_size)))
}
fun withFontSizeResId(expectedResourceId: Int): Matcher<View> {
return object : BoundedMatcher<View, View>(View::class.java) {
private var expectedValueDp: Float = 0.toFloat()
public override fun matchesSafely(view: View): Boolean {
if (view !is TextView) {
return false
}
val actualSizePx = view.textSize
val actualValueDp = AndroidUtil.px2dp(view.getContext(), actualSizePx.toFloat())
expectedValueDp = AndroidUtil.getDimensionDp(view.getContext(), expectedResourceId)
return java.lang.Float.compare(actualValueDp, expectedValueDp) == 0
}
override fun describeTo(description: Description) {
description.appendText("with fontSize: ")
description.appendValue(context.getResources().getString(expectedResourceId))
}
}
}
public static float px2dp(Context context, float px) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float dp = px / ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return dp;
}
public static float getDimensionDp(Context context, int dimenResourceId) {
float dimenDp = (context.getResources().getDimension(dimenResourceId) / context.getResources().getDisplayMetrics().density);
return dimenDp;
}
测试失败,因为“ actualValueDp
” = 17.0,但是“ expectedValueDp
” = 16.9。结果java.lang.Float.compare
!= 0 并且测试失败。
我该如何解决?如何比较textView的文本大小?