testing背景颜色咖啡机器人

是否可以检查背景颜色是否与特浓咖啡相匹配?

我做了一个自定义的匹配器,类似于@Irfan所build议的,谢谢!

public static Matcher<Object> backgroundShouldHaveColor(int expectedColor) { return buttondShouldHaveBackgroundColor(equalTo(expectedColor)); } private static Matcher<Object> buttonShouldHaveBackgroundColor(final Matcher<Integer> expectedObject) { final int[] color = new int[1]; return new BoundedMatcher<Object, Button>( Button.class) { @Override public boolean matchesSafely(final Button actualObject) { color[0] =((ColorDrawable) actualObject.getBackground()).getColor(); if( expectedObject.matches(color[0])) { return true; } else { return false; } } @Override public void describeTo(final Description description) { // Should be improved! description.appendText("Color did not match "+color[0]); } }; } 

Solutions Collecting From Web of "testing背景颜色咖啡机器人"

我不确定,但我们可以检索一些像button和文本视图元素的颜色

 Button button = (Button) findViewById(R.id.my_button); Drawable buttonBackground = button.getBackground(); 

你可以试试这个

 ColorDrawable b_color = (ColorDrawable) button.getBackground(); 

接着

 int color = b_color.getColor(); if (colorID == R.color.green) { log("color is green"); } 

希望这会让你开始。

在我的testing中,我有以下用于testingEditText颜色的匹配器:

 public static Matcher<View> withTextColor(final int color) { Checks.checkNotNull(color); return new BoundedMatcher<View, EditText>(EditText.class) { @Override public boolean matchesSafely(EditText warning) { return color == warning.getCurrentTextColor(); } @Override public void describeTo(Description description) { description.appendText("with text color: "); } }; } 

用法是:

 onView(withId(R.id.password_edittext)).check(matches(withTextColor(Color.RED))); 

这是我在testing中使用的

 public static Matcher<View> withTextColor(final int color) { Checks.checkNotNull(color); return new BoundedMatcher<View, TextView>(TextView.class) { @Override public boolean matchesSafely(TextView textView) { return ContextCompat.getColor(getTargetContext(),color)==textView.getCurrentTextColor(); } @Override public void describeTo(Description description) { description.appendText("with text color: "); } }; } 

并称之为

onView(withId(R.id.price_value))检查(匹配(withTextColor(R.color.black)))。

另一种检查TextView文本颜色的方法可以通过直接来自Espresso的 hasTextColor(int color)

 import static android.support.test.espresso.matcher.ViewMatchers.hasTextColor; onView(withId(R.id.anyTextView)).check(matches(hasTextColor(R.color.red))); 

请注意,此方法目前处于Beta for Espresso 3.0.1版本中

考虑到你有颜色列表,创build它们的数组:

 <?xml version="1.0" encoding="utf-8"?> <resources> <color name="black">#000000</color> <color name="white">#FFFFFF</color> <array name="colors"> <item>@color/black</item> <item>@color/white</item> </array> </resources> 

然后你得到这个数组并循环:

 int[] colors = context.getResources().getIntArray(R.array.colors); for (int i = 0; i < colors.length; i++) { // Compare your color with 'colors[i]' }