Android Studio 3.2。
在我的xml中,我使用ConstraintLayout
<TextView
android:id="@+id/baseTextView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="@dimen/default_margin"
android:layout_marginEnd="@dimen/half_default_margin"
android:text="@string/base"
android:textSize="@dimen/text_view_text_size"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/jsonViewToolBar" />
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/baseTextInputEditText"
style="@style/textViewOneLine"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textSize="@dimen/edit_text_text_size"
app:layout_constraintEnd_toEndOf="@+id/baseTextView"
app:layout_constraintStart_toStartOf="@+id/baseTextView"
app:layout_constraintTop_toBottomOf="@+id/baseTextView" />
<style name="textViewOneLine">
<item name="android:ellipsize">end</item>
<item name="android:maxLines">1</item>
<item name="android:singleLine">true</item>
</style>
您会看到TextView
和TextInputEditText
还有剩余的空白边 = @dimen/default_margin
。
现在,我需要编写Espresso测试以检查baseTextView
和baseTextInputEditText
的边距@dimen/default_margin
@Test
fun baseTextViewMarginStart() {
onView(withId(R.id.baseTextView)).check(matches(withMarginResId(CustomMatchers.Indent.START, R.dimen.default_margin)));
}
@Test
fun baseTextInputEditTextMarginStart() {
onView(withId(R.id.baseTextInputEditText)).check(matches(withMarginResId(CustomMatchers.Indent.START, R.dimen.default_margin)));
}
这是我的自定义匹配器
fun withMarginResId(indent: Indent, expectedResourceId: Int): Matcher<View> {
return object : BoundedMatcher<View, View>(View::class.java) {
private var expectedValueDp: Float = 0.toFloat()
override fun matchesSafely(view: View): Boolean {
expectedValueDp = AndroidUtil.getDimensionDp(view.getContext(), expectedResourceId)
val actualValueDp = getActualMarginDp(view, indent)
return java.lang.Float.compare(actualValueDp, expectedValueDp) == 0
}
override fun describeTo(description: Description) {
description.appendText("with margin(dp): ")
description.appendValue(expectedResourceId)
}
}
}
public static float getDimensionDp(Context context, int dimenResourceId) {
float dimenDp = (context.getResources().getDimension(dimenResourceId) / context.getResources().getDisplayMetrics().density);
return dimenDp;
}
第一次测试是通过,但是第二次测试是失败。
为什么?