Issue
In Android UI testing we had the ViewAsserts class which is deprecated in API level 24.
The class had some methods such as assertHorizontalCenterAligned to test if a view is horizontally centered within another view.
What is the alternative for such a method in the new Espresso PositionAssertions?
It has Assertions for left,right,top and bottom alignment, but no center assertions.
Solution
To begin, my answer doesn't use PositionAssertions, but you said it is okay
I created my a custom ViewAsserts, and it works on any Android platform
Your view
Let's say you have the folowing xml view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="merchantapp.ul.com.myapplication.MainActivity">
<RelativeLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/lll"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_centerInParent="true"
android:orientation="vertical"></LinearLayout>
</RelativeLayout>
</RelativeLayout>
The view with id lll
is in the center of the view with id ll
Custom ViewAsserts
Create class HorizontalViewAssertion
public class HorizontalViewAssertion extends TypeSafeMatcher<View> {
private final View view;
private HorizontalViewAssertion (View view) {
this.view = view;
}
public static HorizontalViewAssertion alignHorizantalWith(View view) {
return new HorizontalViewAssertion(view);
}
@Override
protected boolean matchesSafely(View item) {
float centerX1 = item.getX() + (((float)item.getWidth())/2.0f);
float centerX2 = this.view.getX() + (((float)this.view.getWidth())/2.0f);
if ( (Math.abs(centerX1 - centerX2)) <= 1)
return true;
return false;
}
@Override
public void describeTo(Description description) {
}
}
Your test unit
Create your test unit
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ActivityTestRule<>(MainActivity.class);
@Test
public void testHorizantalCenter() {
onView(withId(R.id.lll)).check(ViewAssertions.matches(alignHorizantalWith(mActivityRule.getActivity().findViewById(R.id.ll))));
}
}
The test will pass
Description
The idea is simple, we have two views, let's call them view1
and view2
Calculate the horizontal x for the center of both views by getting the x axis and summing it to half of the width
Then check if these two centers are the same (Well, I am not checking if they are equal, but I am checking if the difference between them is less than 1 and that's because of dividing in the floating point. From math point of view, the difference will never more than 0.5)
I hope that's good for you
Answered By - William Kinaan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.