下面列出了怎么用android.support.test.espresso.ViewAssertion的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void clickOnElection() throws Exception {
final Election e = electionActivity.getAdapter().getItem(1);
onData(instanceOf(Election.class)) // We are using the position so don't need to specify a data matcher
.inAdapterView(withId(R.id.election_list)) // Specify the explicit id of the ListView
.atPosition(1) // Explicitly specify the adapter item to use
.perform(click());
// intended(hasComponent(MainActivity.class.getName()));
onView(withId(R.id.app_bar)).check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
assertEquals(((Toolbar) view).getTitle(), e.getKind());
assertEquals(((Toolbar) view).getSubtitle(), e.getPlace());
}
});
}
@Test
public void searchCityAndClick() throws Exception {
List<Election> unfilteredList = electionActivity.getAdapter().getList();
onView(withId(R.id.search)).perform(click());
final Election toClick = unfilteredList.get(0);
onView(withId(android.support.design.R.id.search_src_text)).perform(typeText(toClick.getPlace()));
onView (withId (R.id.election_list)).check (ViewAssertions.matches (new Matchers().withListSize (1)));
onData(instanceOf(Election.class))
.inAdapterView(withId(R.id.election_list))
.atPosition(0)
.perform(click());
// intended(hasComponent(MainActivity.class.getName()));
onView(withId(R.id.app_bar)).check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
assertEquals(((Toolbar) view).getTitle(), toClick.getKind());
assertEquals(((Toolbar) view).getSubtitle(), toClick.getPlace());
}
});
}
public static ViewAssertion flexGridHasCode(final List<CodeLine> expectedCodeLines)
{
return new ViewAssertion()
{
@Override
public void check(View view, NoMatchingViewException noViewException)
{
FlexGrid flexGrid = (FlexGrid) view;
List<CodeLine> actualCodeLines = (List<CodeLine>) flexGrid.getItemsSource();
for (int i = 0; i < expectedCodeLines.size(); i++)
{
CodeLine expected = expectedCodeLines.get(i);
CodeLine actual = actualCodeLines.get(i);
assertEquals(expected.getCodeText(), actual.getCodeText());
}
}
};
}
/**
* Check that this item exist.
*
* Is true when adapter has matching item ignores the display state.
*
* @since Espresso Macchiato 0.6
*/
public void assertExist() {
findRecyclerView().check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
if (noViewFoundException != null) {
throw noViewFoundException;
}
RecyclerView recyclerView = (RecyclerView) view;
if (index >= recyclerView.getAdapter().getItemCount()) {
throw new AssertionFailedError("Requested item should exist.");
}
}
});
}
@Test
public void testAutoFocus() {
onView(withId(R.id.camera))
.check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
CameraView cameraView = (CameraView) view;
// This can fail on devices without auto-focus support
assertThat(cameraView.getAutoFocus(), is(true));
cameraView.setAutoFocus(false);
assertThat(cameraView.getAutoFocus(), is(false));
cameraView.setAutoFocus(true);
assertThat(cameraView.getAutoFocus(), is(true));
}
});
}
private static ViewAssertion showingPreview() {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
CameraView cameraView = (CameraView) view;
TextureView textureView = cameraView.findViewById(R.id.texture_view);
Bitmap bitmap = textureView.getBitmap();
int topLeft = bitmap.getPixel(0, 0);
int center = bitmap.getPixel(bitmap.getWidth() / 2, bitmap.getHeight() / 2);
int bottomRight = bitmap.getPixel(
bitmap.getWidth() - 1, bitmap.getHeight() - 1);
assertFalse("Preview possibly blank: " + Integer.toHexString(topLeft),
topLeft == center && center == bottomRight);
}
};
}
public static ViewAssertion checkMessagesOnlyFromToday() {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
RecyclerMessageAdapter recyclerMessageAdapter = (RecyclerMessageAdapter) rv.getAdapter();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("OfDate-" + (new Date()).toString() + " { ");
for (int index = 0; index < recyclerMessageAdapter.getItemCount(); index++) {
if (recyclerMessageAdapter.getItem(index) instanceof Message) {
Message message = (Message) recyclerMessageAdapter.getItem(index);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.US);
stringBuilder.append(message.getID() + "-" + sdf.format(message.getTimestamp()) + " , ");
assertTrue("This message is not of today ID=" + message.getID() + ":" + message.getIdForHolder() + "\ncontent=" + message.getContent(), DateUtils.isToday(message.getTimestamp().getTime()));
}
}
stringBuilder.append(" }");
printLogInPartsIfExceeded(stringBuilder, "checkMessagesOnlyFromToday");
}
};
}
public static ViewAssertion hasViewWithTextAtPosition(final int index, final CharSequence text) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
ArrayList<View> outviews = new ArrayList<>();
rv.findViewHolderForAdapterPosition(index).itemView.findViewsWithText(outviews, text,
FIND_VIEWS_WITH_TEXT);
Truth.assert_().withFailureMessage("There's no view at index " + index + " of recyclerview that has text : " + text)
.that(outviews).isNotEmpty();
}
};
}
public static ViewAssertion doesntHaveViewWithText(final String text) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
ArrayList<View> outviews = new ArrayList<>();
for (int index = 0; index < rv.getAdapter().getItemCount(); index++) {
rv.findViewHolderForAdapterPosition(index).itemView.findViewsWithText(outviews, text,
FIND_VIEWS_WITH_TEXT);
if (outviews.size() > 0) break;
}
Truth.assertThat(outviews).isEmpty();
}
};
}
@Test
public void atElectionActivity() throws Exception {
onView(withId(R.id.app_bar)).check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
assertEquals(((Toolbar) view).getTitle(), "Choose election");
}
});
}
/**
* @param enabled Whether the view should be matched to be enabled or not.
* @return A {@link ViewAssertion} that asserts that a view should be matched
* to be enabled or disabled.
*/
private static ViewAssertion matchesIsEnabled(boolean enabled) {
// TODO: When we're comfortable with the APIs, we can statically import them and
// make direct calls to these methods and cut down on the verbosity, instead of
// writing helper methods that wrap these APIs.
return ViewAssertions.matches(enabled ? ViewMatchers.isEnabled() : Matchers.not(ViewMatchers.isEnabled()));
}
public static ViewAssertion flexGridReadOnly(final boolean expected)
{
return new ViewAssertion()
{
@Override
public void check(View view, NoMatchingViewException noViewException)
{
FlexGrid flexGrid = (FlexGrid) view;
assertEquals(expected, flexGrid.isReadOnly());
}
};
}
public static ViewAssertion mockDrawable(final String expectedTag)
{
return new ViewAssertion()
{
@Override
public void check(View view, NoMatchingViewException noViewException)
{
String tag = (String) ((MockDrawable) ((ImageView) view).getDrawable()).getTag();
assertEquals(expectedTag, tag);
}
};
}
public static ViewAssertion withDrawable(@DrawableRes final int expectedResourceId)
{
return new ViewAssertion()
{
@Override
public void check(View view, NoMatchingViewException noViewException)
{
@DrawableRes int tag = (int) ((MockDrawable) ((ImageView) view).getDrawable()).getTag();
assertEquals(expectedResourceId, tag);
}
};
}
public static ViewAssertion haveItemCount(final int count) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
StringDescription description = new StringDescription();
description.appendText("'");
if (noViewFoundException != null) {
description.appendText(String.format(
"' check could not be performed because view '%s' was not found.\n",
noViewFoundException.getViewMatcherDescription()));
Log.e(TAG, description.toString());
throw noViewFoundException;
} else {
int actualCount = -1;
if (view instanceof RecyclerView) {
actualCount = getItemCount((RecyclerView) view);
}
if (actualCount == -1) {
throw new AssertionError("Cannot get view item count.");
} else if (actualCount != count) {
throw new AssertionError("View has " + actualCount +
"items while expected " + count);
}
}
}
};
}
public static ViewAssertion assertIsExpanded() {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
AppBarLayout appBarLayout = (AppBarLayout) view;
boolean isFullExpanded = appBarLayout.getHeight() - appBarLayout.getBottom() == 0;
ViewMatchers.assertThat("is full expanded", isFullExpanded, is(true));
}
};
}
@Test
public void testFacing() {
onView(withId(R.id.camera))
.check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
CameraView cameraView = (CameraView) view;
assertThat(cameraView.getFacing(), is(CameraView.FACING_BACK));
cameraView.setFacing(CameraView.FACING_FRONT);
assertThat(cameraView.getFacing(), is(CameraView.FACING_FRONT));
}
})
.perform(waitFor(1000))
.check(showingPreview());
}
@Test
public void testFlash() {
onView(withId(R.id.camera))
.check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
CameraView cameraView = (CameraView) view;
assertThat(cameraView.getFlash(), is(CameraView.FLASH_AUTO));
cameraView.setFlash(CameraView.FLASH_TORCH);
assertThat(cameraView.getFlash(), is(CameraView.FLASH_TORCH));
}
});
}
public static ViewAssertion checkOrderOfMessages(final ZulipActivity zulipActivity) {
//ZulipActivity is needed for generating detailed info about position if doesn't matches
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noMatchingViewException) {
if (!(view instanceof RecyclerView)) {
throw noMatchingViewException;
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('{');
RecyclerMessageAdapter recyclerMessageAdapter = (RecyclerMessageAdapter) ((RecyclerView) view).getAdapter();
for (int i = 0; i < recyclerMessageAdapter.getItemCount() - 1; i++) {
Object object = recyclerMessageAdapter.getItem(i);
if (object instanceof Message) {
if (recyclerMessageAdapter.getItem(i + 1) instanceof Message) {
boolean checkOrder = (((Message) object).getID() < ((Message) recyclerMessageAdapter.getItem(i + 1)).getID());
assertTrue(generateDetailedInfoForOrder(((Message) object), ((Message) recyclerMessageAdapter.getItem(i + 1)), zulipActivity, i), checkOrder);
}
stringBuilder.append(((Message) object).getID() + ",");
} else if (object instanceof MessageHeaderParent) {
stringBuilder.append("} | { ");
}
}
stringBuilder.append('}');
printLogInPartsIfExceeded(stringBuilder, "checkOrderOfMessages");
}
};
}
public static ViewAssertion checkIfMessagesMatchTheHeaderParent(final ZulipActivity zulipActivity) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noMatchingViewException) {
if (!(view instanceof RecyclerView)) {
throw noMatchingViewException;
}
RecyclerMessageAdapter recyclerMessageAdapter = (RecyclerMessageAdapter) ((RecyclerView) view).getAdapter();
String lastHolderId = null;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < recyclerMessageAdapter.getItemCount() - 1; i++) {
Object object = recyclerMessageAdapter.getItem(i);
if (object instanceof MessageHeaderParent) {
lastHolderId = ((MessageHeaderParent) object).getId();
stringBuilder.append("} \'MHP\'-\'" + lastHolderId + " {");
} else if (object instanceof Message) {
Message message = (Message) object;
boolean checkOrder = (lastHolderId.equals(message.getIdForHolder()));
assertTrue(generateDetailDebugInfoForCorrectHeaderParent(message, zulipActivity, lastHolderId, i), checkOrder);
stringBuilder.append(message.getIdForHolder() + "-" + message.getID() + " , ");
}
}
stringBuilder.append('}');
printLogInPartsIfExceeded(stringBuilder, "checkIfMessagesMatchTheHeaderParent");
}
};
}
public static ViewAssertion checkIfBelongToSameNarrow(final ZulipActivity zulipActivity) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noMatchingViewException) {
if (!(view instanceof RecyclerView)) {
throw noMatchingViewException;
}
RecyclerMessageAdapter recyclerMessageAdapter = (RecyclerMessageAdapter) ((RecyclerView) view).getAdapter();
String lastHolderId = null;
int headerParentsCount = 0;
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < recyclerMessageAdapter.getItemCount() - 1; i++) {
Object object = recyclerMessageAdapter.getItem(i);
if (object instanceof MessageHeaderParent) {
headerParentsCount++;
assertTrue(generateDetailInfoSameNarrow((MessageHeaderParent) object, i, zulipActivity, lastHolderId), headerParentsCount <= 1);
lastHolderId = ((MessageHeaderParent) object).getId();
stringBuilder.append(lastHolderId + " { ");
} else if (object instanceof Message) {
boolean checkId = ((Message) object).getIdForHolder().equals(lastHolderId);
assertTrue(generateDetailInfoSameNarrow(((Message) object), zulipActivity, lastHolderId, i), checkId);
stringBuilder.append(((Message) object).getIdForHolder() + " , ");
}
}
stringBuilder.append(" }");
printLogInPartsIfExceeded(stringBuilder, "checkIfBelongToSameNarrow");
}
};
}
public static ViewAssertion hasItemsCount() {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
assertThat("Items less than 2, which means no E-Mails!", rv.getAdapter().getItemCount(), org.hamcrest.Matchers.greaterThan(2));
}
};
}
public static ViewAssertion hasItemsCount(final int count) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
if (rv.getAdapter() == null && count == 0) {
return;
}
Truth.assertThat(rv.getAdapter().getItemCount()).isEqualTo(count);
}
};
}
public static ViewAssertion hasHolderItemAtPosition(final int index,
final Matcher<RecyclerView.ViewHolder> viewHolderMatcher) {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException e) {
if (!(view instanceof RecyclerView)) {
throw e;
}
RecyclerView rv = (RecyclerView) view;
Assert.assertThat(rv.findViewHolderForAdapterPosition(index), viewHolderMatcher);
}
};
}
static Activity getCurrentActivity() {
final Activity[] activity = new Activity[1];
onView(isRoot()).check(new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noViewFoundException) {
activity[0] = (Activity) view.findViewById(android.R.id.content).getContext();
}
});
return activity[0];
}
@NonNull
final ViewInteraction check(final ViewAssertion viewAssert) {
return Espresso.onView(get()).check(viewAssert);
}
@Override
public android.support.test.espresso.ViewInteraction check(ViewAssertion viewAssert) {
return cortado.check(viewAssert);
}
public static ViewAssertion adapterItemCountEquals(int count) {
return new ItemCountAssertion(ItemCountAssertion.MODE_EQUALS, count);
}
public static ViewAssertion adapterItemCountLowerThan(int count) {
return new ItemCountAssertion(ItemCountAssertion.MODE_LESS_THAN, count);
}
public static ViewAssertion doesNotHaveFlowService(final String serviceName) {
return new FlowServiceIsNull(serviceName, false);
}