Barista makes developing UI test faster, easier and more predictable. Built on top of Espresso

Overview

Barista

The one who serves a great Espresso

CI Hex.pm

Barista makes developing UI test faster, easier and more predictable. Built on top of Espresso, it provides a simple and discoverable API, removing most of the boilerplate and verbosity of common Espresso tasks. You and your Android team will write tests with no effort.

Download

Import Barista as a testing dependency:

androidTestImplementation('com.adevinta.android:barista:4.1.0') {
  exclude group: 'org.jetbrains.kotlin' // Only if you already use Kotlin in your project
}

You might need to include the Google Maven repository, required by Espresso 3:

repositories {
    google()
}

Barista already includes espresso-core and espresso-contrib. If you need any other Espresso package you can add them yourself.

API Overview

Barista’s Interactions API

Click widgets

clickOn(R.id.button);
clickOn(R.string.button_text);
clickOn("Next");
clickBack();

Long click widgets

longClickOn(R.id.button);
longClickOn(R.string.button_text);
longClickOn("Next");

Click menu items, with or without overflow

clickMenu(R.id.menu_item);

Open the overflow menu without clicking any item

openMenu();

Writing into widgets

writeTo(R.id.edittext, "A great text"); // Ignores the EditText restrictions like maxLength and textFilter. It's blazing fast.
typeTo(R.id.edittext, "A great text"); // Honors the EditText restrictions like maxLength and textFilter. It slows down the test.
writeToAutoComplete(R.id.autocomplete, "Another great text");
clearText(R.id.edittext)

Operate on ListViews and RecyclerViews indistinctly by position

clickListItem(R.id.list, 4);
clickListItemChild(R.id.list, 3, R.id.row_button);
scrollListToPosition(R.id.list, 4);

clickSpinnerItem(R.id.spinner, 1);

Select items on RadioButtons

clickRadioButtonItem(R.id.radiogroup, R.id.radio_item);
clickRadioButtonItem(R.id.radiogroup, "The radio text");
clickRadioButtonPosition(R.id.radiogroup, 42);

Pick data on pickers

setDateOnPicker(1986, 03, 23);
setTimeOnPicker(17, 2);

Interact with dialogs

clickDialogPositiveButton();
clickDialogNeutralButton();
clickDialogNegativeButton();

Scroll on scrolls and pagers

scrollTo(R.id.far_away_widget);
scrollTo(R.string.text);
scrollTo("A widget with this text");
scrollTo(withTagValue(is("tagName"))) // using custom matchers
swipeViewPagerForward();
swipeViewPagerBack();

Interact with the navigation drawer

openDrawer();
openDrawerWithGravity(Gravity.RIGHT);
closeDrawer();
closeDrawerWithGravity(Gravity.RIGHT);

Interact with SeekBars

setProgressTo(R.id.seek_bar, 5);
setProgressToMin(R.id.seek_bar);
setProgressToMax(R.id.seek_bar);

Pull to refresh in SwipeRefreshLayout

refresh(R.id.swipe_refresh);
refresh(); // Id is optional. Barista will find it for you.

Close or press ime actions on the Keyboard

closeKeyboard()
pressImeActionButton()

And another tricky feature, but try not to use it

sleep(2000);
sleep(2, SECONDS);

Barista’s Assertions API

Is this view displayed?

assertDisplayed("Hello world");
assertDisplayed(R.string.hello_world);
assertDisplayed(R.id.button);
assertDisplayed(R.id.button, "Hello world")
assertDisplayed(R.id.button, R.string.hello_world)

// on ListViews and RecyclerViews by position
assertDisplayedAtPosition(R.id.list, 0, "text");
assertDisplayedAtPosition(R.id.list, 0, R.id.text_field, "text");
assertDisplayedAtPosition(R.id.list, 0, R.string.hello_world);
assertDisplayedAtPosition(R.id.list, 0, R.id.text_field, R.string.hello_world);
assertDrawableDisplayedAtPosition(R.id.recycler, 0, R.id.imageview, R.drawable.ic_barista);

// you can also pass custom matchers
assertDisplayed(withTagValue(is("tagName")))

// ...or not?
assertNotDisplayed("Hello world");
assertNotDisplayed(R.string.hello_world);
assertNotDisplayed(R.id.button);
assertNotDisplayed(R.id.button, "Hello world")
assertNotDisplayed(R.id.button, R.string.hello_world)
// you can also pass custom matchers
assertNotDisplayed(withTagValue(is("tagName")))

Is this view enabled?

assertEnabled("Hello world");
assertEnabled(R.string.hello_world);
assertEnabled(R.id.button);

// ...or not?
assertDisabled("Hello world");
assertDisabled(R.string.hello_world);
assertDisabled(R.id.button);

Hope this view doesn't exist!

assertNotExist("Hello world");
assertNotExist(R.string.hello_world);
assertNotExist(R.id.button);

Is the expected checkbox checked?

assertChecked("Checked checkbox");
assertChecked(R.string.checked_checkbox);
assertChecked(R.id.checkbox);

// ...or not?
assertUnchecked("Unchecked checkbox");
assertUnchecked(R.string.unchecked_checkbox);
assertUnchecked(R.id.checkbox);

Is this view clickable?

assertClickable("Hello world")
assertClickable(R.string.hello_world)
assertClickable(R.id.button)

// ...or not?
assertNotClickable("Hello world")
assertNotClickable(R.string.hello_world)
assertNotClickable(R.id.button)

Does this view have the focus?

assertFocused(R.id.focused_view)
assertFocused("Button")

// ...or not?
assertNotFocused(R.id.focused_view)
assertNotFocused("Button")

Is this ImageView showing a drawable?

assertHasAnyDrawable(R.id.image_view);
assertHasDrawable(R.id.image_view, R.drawable.ic_barista);

// ...or not?
assertHasNoDrawable(R.id.image_view);

Does this View have a background?

assertHasAnyBackground(R.id.view);
assertHasBackground(R.id.view, R.drawable.ic_barista);

// ...or not?
assertHasNoBackground(R.id.view);

Does this View have content description?

assertHasContentDescription(R.id.anyView);
assertContentDescription(R.id.anyView, R.string.content_description);
assertContentDescription(R.id.anyView, "Some text");

Is this List empty? How many items does it have?

// Works with both ListView and RecyclerView
assertListNotEmpty(R.id.list)
assertListItemCount(R.id.list, 5)

// You can also pass custom assertions
assertCustomAssertionAtPosition(R.id.list, 0, customViewAssertion);

What's the state of the Drawer?

assertDrawerIsOpen();
assertDrawerIsOpenWithGravity(Gravity.RIGHT);
assertDrawerIsClosed();
assertDrawerIsClosedWithGravity(Gravity.RIGHT);

Check TextInputLayout and EditText's hints

assertHint(R.id.edittext, R.string.hint);
assertHint(R.id.edittext, "Hint");

Check TextInputLayout and EditText's errors

assertErrorDisplayed(R.id.edittext, R.string.error);
assertErrorDisplayed(R.id.edittext, "Error message");

assertNoErrorDisplayed(R.id.edittext, R.string.error);
assertNoErrorDisplayed(R.id.edittext, "Error message");

Check TextInputLayout's assistive helper text

assertAssistiveText(R.id.textinputlayout, R.string.helper_text);
assertAssistiveText(R.id.textinputlayout, "Helper text");

Check if text on screen contains given text

assertContains("text");
assertContains(R.string.text);
assertContains(R.id.textview, "text");
assertContains(R.id.textview, R.string.text);

// ...or not?
assertNotContains("text");
assertNotContains(R.string.text);
assertNotContains(R.id.textview, "text");
assertNotContains(R.id.textview, R.string.text);

Check text is given color

assertTextColorIs(R.id.some_red_text, R.color.red);
assertTextColorIs(R.id.some_color_list_text, R.color.state_list);

// ...or not?
assertTextColorIsNot(R.id.some_red_text, R.color.blue);
assertTextColorIsNot(R.id.some_color_list_text, R.color.another_state_list);

assertTextColorIs and its variant assertTextColorIsNot work with:

  • Color int: Color.parse("#ff00ff")
  • Color resource: R.color.green
  • Color attribute: R.attr.colorPrimary

Also Barista can check colors parsed from declarable-style custom attribute:

assertTextColorIs(R.id.customTextView, R.styleable.SampleCustomView, R.style.SampleCustomStyle, R.styleable.SampleCustomView_customColor);

// ...or not?
assertTextColorIsNot(R.id.customTextView, R.styleable.SampleCustomView, R.style.SampleCustomStyle_Green, R.styleable.SampleCustomView_customColor);

Check recyclerView item count against expected item count

assertRecyclerViewItemCount(R.id.recycler, 10);

Is this ProgressBar/SeekBar progress?

assertProgress(R.id.seek_bar, 5)
assertProgressIsMin(R.id.seek_bar)
assertProgressIsMax(R.id.seek_bar)

And another tricky feature

assertThatBackButtonClosesTheApp();

Custom assertions

If you have a special case not covered by the given assertions API, we encourage you to assert these special cases with our custom assertions API. It's a convenient way to replace plain Matchers with complex assertions. With Barista, you can match any kind of view by knowing its type and passing its viewId, text, or a Matcher . Once you matched it, you will be able to assert all its properties without adding any complex Matcher to your project.

(R.id.radioGroup) { it.checkedRadioButtonId == R.id.option1 } // Matching a Progressbar by a Matcher assertAny (withId(R.id.progressBar)) { it.progress == 42 } // You can also define the assertion description that will be shown if the assertion fails assertAny (R.id.radioGroup, "selected option is the second one") { it.checkedRadioButtonId == R.id.option1 } ">
// Matching a Button by text
assertAny<Button>("Save") {
    it.enabled == true
}

// Matching a RadioGroup by id
assertAny<RadioGroup>(R.id.radioGroup) {
    it.checkedRadioButtonId == R.id.option1
}

// Matching a Progressbar by a Matcher
assertAny<Progressbar>(withId(R.id.progressBar)) {
    it.progress == 42
}

// You can also define the assertion description that will be shown if the assertion fails
assertAny<RadioGroup>(R.id.radioGroup, "selected option is the second one") {
    it.checkedRadioButtonId == R.id.option1
}

Mocking the Intent results

Mocking the Android Camera Intent is a tricky thing to do. To accomplish it in no time, Barista gives a way to do it in one line: the method mockAndroidCamera(). This method does all the magic to mock the result of the camera. One more thing to do: you have to call Intents.init() before calling mockAndroidCamera(), and Intents.release() after doing the action that launches the camera. You could also use IntentsTestRule instead of the common ActivityTestRule to skip it, but as we recommend the use of BaristaRule, it's easier to just call both methods manually when needed.

Here's an example to copy paste:

try {
  Intents.init();
  BaristaIntents.mockAndroidCamera();
  clickOn(R.id.launch_camera);
} finally {
  Intents.release();
}

Runtime Permissions

The new Marshmallow permissions system requires checking for permissions at runtime. As Espresso can't interact with the system dialog, Barista offers a way to allow permissions when needed.

PermissionGranter.allowPermissionsIfNeeded(Manifest.permission.GET_ACCOUNTS);
PermissionGranter.allowPermissionOneTime(Manifest.permission.GET_ACCOUNTS);

Useful test rules

Barista includes a set of useful test rules to help you:

Resetting app data

As tests should be isolated, they need to set the environment before running. Espresso doesn't help achieving it but Barista offers a set of rules to clear the app's data before running each test.

// Clear all app's SharedPreferences
@Rule public ClearPreferencesRule clearPreferencesRule = new ClearPreferencesRule();

// Delete all tables from all the app's SQLite Databases
@Rule public ClearDatabaseRule clearDatabaseRule = new ClearDatabaseRule();

// Delete all files in getFilesDir() and getCacheDir()
@Rule public ClearFilesRule clearFilesRule = new ClearFilesRule();

Dealing with Flaky tests

We should try to write deterministic tests, but when everything else fails Barista helps you deal with flaky tests using a specific ActivityTestRule and a couple of annotations that repeat your tests multiple times.

// Use a RuleChain to wrap your ActivityTestRule with a FlakyTestRule
private ActivityTestRule<FlakyActivity> activityRule = new ActivityTestRule<>(FlakyActivity.class);
private FlakyTestRule flakyRule = new FlakyTestRule();

@Rule
public RuleChain chain = RuleChain.outerRule(flakyRule)
    .around(activityRule);


// Use @AllowFlaky to let flaky tests pass if they pass any time.
@Test
@AllowFlaky(attempts = 5)
public void some_flaky_test() throws Exception {
  // ...
}

// Use @Repeat to avoid flaky tests from passing if any repetition fails.
@Test
@Repeat(times = 5)
public void some_important_test() throws Exception {
  // ...
}

One rule to rule them all

All previous rules can be added at the same time by just adding the BaristaRule.

@Rule
public BaristaRule<MyActivity> baristaRule = BaristaRule.create(MyActivity.class);

//...

baristaRule.launchActivity();

The rule assumes some sane defaults:

  • Retry flaky tests: 10 attempts
  • Launch activity automatically: false
  • Initial touch mode enabled: true
  • Clear preferences
  • Clear databases
  • Clear files

Writing tests in Kotlin?

Check this link to know how to use @Rule in Kotlin.

Magic that Barista does for you

In order to speed up testing, Barista keeps in mind some considerations.

  • Scrolls when needed: Interacting with Espresso in a ScrollView requires you to scroll to each view, which sometimes doesn't work the first time. Also trying to scroll outside a ScrollView produces an Exception, forcing you to change the test depending on the layout. To keep tests simpler, Barista scrolls automatically before interacting with any View, and only does it if needed.
  • Scrolls on all views: Barista scrolls on all scrollable views, including NestedScrollView. Espresso only handles ScrollView and HorizontalScrollView, so people need to open questions on StackOverflow like this. Or... just use Barista.
  • Just interacts with displayed Views: Interacting with Views inside a ViewPager throws AmbiguousViewMatcherException, because the views you interact with will be potentially repeated on different pages. Barista only interacts with displayed widgets, so you can focus on the behavior instead of wasting time on details.

Contributing

We welcome contributions! If you found a bug or have a feature request, feel free to open an issue to discuss it. Remember that bugs reported with a reproducible test are more likely to be investigated and fixed. You can also submit a Pull Request.

Formatting

We use our company's IntelliJ code style for the project, which is very similar to the official Kotlin Android code style. When submitting code please make sure you use the proper format. You can install the code style into Android Studio by running the script in ./config/androidstudio/install-codestyle.sh. Then restart Android Studio and pick the "BaristaAndroid" schema in preferences.

Prefer Java-written test classes

As most parts of Barista are Java-compatible, please do write Java tests when possible. Writing them in Kotlin might lead to using Kotlin-only shortcuts, breaking the Java compatibility Barista aims for.

License

Apache License, Version 2.0 (the "License")

Comments
  • Fake camera calls intents

    Fake camera calls intents

    Based on https://github.com/SchibstedSpain/Barista/pull/155

    I've used a custom matcher<Intent> to retrieve the uri form MediaStore.EXTRA_OUTPUT, and creates a fake Bitmap on it

    review-please 
    opened by alorma 37
  • Hamcrest old version causes: java.lang.NoSuchMethodError: No static method allOf

    Hamcrest old version causes: java.lang.NoSuchMethodError: No static method allOf

    Please consider making a Pull Request if you are capable of doing so.

    Library Version:

    3.5.0

    Describe the Bug:

    When I use the assertListItemCount(R.id.list, 5) method and some other methods from Barista I get the following exception:

    java.lang.NoSuchMethodError: No static method allOf(Lorg/hamcrest/Matcher;Lorg/hamcrest/Matcher;Lorg/hamcrest/Matcher;)Lorg/hamcrest/Matcher; in class Lorg/hamcrest/CoreMatchers; or its super classes (declaration of 'org.hamcrest.CoreMatchers' appears in /data/app/com.myapp.android.debug.test-teuB7mkareqg4fXqftwOghQ==/base.apk!classes3.dex)
    at com.schibsted.spain.barista.interaction.BaristaListInteractions.findRecyclerMatcher(BaristaListInteractions.kt:118)
    at com.schibsted.spain.barista.assertion.BaristaListAssertions.assertListItemCount(BaristaListAssertions.kt:33)
    ...
    at java.lang.reflect.Method.invoke(Native Method)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at androidx.test.internal.runner.junit4.statement.RunBefores.evaluate(RunBefores.java:80)
    at androidx.test.internal.runner.junit4.statement.RunAfters.evaluate(RunAfters.java:61)
    at androidx.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:531)
    at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:288)
    at org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:282)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.lang.Thread.run(Thread.java:764)
    

    I did some investigation and the problem is that we have Hamcrest v2.2 in our project and Barista uses Hamcrest v1.3 which comes transitively from Espresso dependencies. If I downgrade Hamcrest to v1.3 in the project dependencies it works fine.

    Is it possible to start using Hamcrest v2.2 in Barista to make it possible to use in project with the updated library? I can open a PR if it's fine for you to get updated.

    Steps to reproduce the bug:

    Expected Behavior:

    opened by rsavin 22
  • Problem when trying to click a button that is behind the keyboard

    Problem when trying to click a button that is behind the keyboard

    In a test for our login screen, I found an "error" in the library when writing into an EditText/AutoCompleteTextView, the "problem" appears when the screen has a button at the bottom and it is hidden behind the keyboard.

    screenshot_1512221877 screenshot_1512221887

    We have a test like this:

    BaristaEditTextInteractions.writeTo(R.id.email, "[email protected]")
    BaristaEditTextInteractions.writeTo(R.id.password, "")
    BaristaClickInteractions.clickOn(R.id.submit)
    

    But we get this is the error because we are trying to click a button that is not visible and it's hidden behind the keyboard.

    com.schibsted.spain.barista.internal.failurehandler.BaristaException: 
    Could not click on view with id: com.trov.maui.staging:id/submit
    

    My proposal would be to close by default the keyboard after the text has been written, also it could provide the option to submit from the keyboard.

    I've already created some extensions for this so I will open a PR to show the proposed solution.'

    wip 
    opened by jamesbluecrow 16
  • Fix the matching position counter for atPosition

    Fix the matching position counter for atPosition

    The counter named "matchingPosition" did not reset to 0, after the method "atPosition" was called once. As you can find in the test cases I included, when you create a Matcher object with atPosition, and use it once,you weren't able to use it the second time since the matcher tried to find the object again but the counter started from where it remained instead of 0, resulting in a NoMatchingViewException(in this library, it corresponds to BaristaException). Also the method in ViewTreeAnalyzer fails to find all the views the matcher compares our target against, so I wrote a new method to find the number of views that are compared with our target.

    opened by CemGalioglu 15
  • Espresso Intents

    Espresso Intents

    Description what you'd like to happen:

    assertIntended(
        clickListItem(R.id.rv_users, 0), // mandatory
        UserDetailActivity::class.java.name, // mandatory
        intentData // optional
    )
    

    Example espresso code if available

    Intents.init()
    // ... clickListItem(R.id.rv_users, 0)
    intended(
        allOf(
            hasComponent(UserDetailActivity::class.java.name)
        )
    )
    Intents.release()
    
    opened by theapache64 14
  • Create compose base

    Create compose base

    Create barista-compose module and create first assertions.

    assertDisplayed("Some text") && assertDisplayed(R.string.some_string)
    assertNotDisplayed("Some text") && assertNotDisplayed(R.string.some_string)
    

    Both depending on ComposeTestRule and `SemantincNodeInteraction``

    So test will look:

      @Test
      fun assertIsDisplayed_StringTest() {
        composeTestRule.setContent {
          TextComposable("Hello world")
        }
    
        composeTestRule.assertDisplayed("Hello world")
      }
    
      @Test
      fun assertDisplayed_ResourceTest() {
        composeTestRule.setContent {
          TextComposable(stringResource(R.string.app_name))
        }
    
        composeTestRule.assertNotDisplayed(R.string.next)
      }
    
    opened by alorma 13
  • writeTo(R.id.edit_text,

    writeTo(R.id.edit_text, "String with Spaces") does not respect the EditText filter, to disallow specfic characters

    Please consider making a Pull Request if you are capable of doing so.

    Library Version:

    3.9.0

    dependencies {
        ...
        androidTestImplementation('com.schibsted.spain:barista:3.9.0') {
            exclude group: 'org.jetbrains.kotlin' // Only if you already use Kotlin in your project
        }
    }
    

    Describe the Bug:

    Layout has:

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusableInTouchMode="true"
        android:hint="Type some text with spaces"
        android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
        android:inputType="textFilter"
        android:singleLine="true"
        android:imeOptions="actionNext" />
    

    Notice the android:digits and android:inputType which create a filter to allow or disallow certain characters. Spaces are disallowed. See: https://stackoverflow.com/questions/33993041/android-disable-space-only-for-edittext

    writeTo(R.id.edit_text, "String with Spaces") adds spaces to the EditText which has disallowed spaces.

    Unit test has:

    // Barista methods:
    writeTo(R.id.edit_text, "String With Spaces")
    assertDisplayed(R.id.edit_text, "StringWithSpaces") // assertion fails
    
    // Espresso methods:
    onView(withId(R.id.edit_text)).perform(typeText("String With Spaces"))
    onView(withId(R.id.edit_text)).check(matches(withText("StringWithSpaces"))) // assertion passes
    

    Steps to reproduce the bug:

    1. Create an EditText or TextInputEditText which uses a filter and restricted digits, like the example above. See https://stackoverflow.com/questions/33993041/android-disable-space-only-for-edittext
    2. Write a Barista test to type characters into this EditText. The characters should include some of the disallowed characters, like spaces.
    3. Assert with Barista that the EditText does not contain the disallowed characters

    Expected Behavior:

    Barista should not insert the disallowed characters, because a user would not be able to do this with the on-screen keyboard. The Barista assertion for the correct string should pass. Barista's writeTo() should behave like Espresso's typeText().

    Actual Behavior:

    Barista inserts the disallowed characters into the EditText. The Barista assertion for the correct string fails.

    opened by ozmium 13
  • Program type already present: androidx.test.InstrumentationRegistry

    Program type already present: androidx.test.InstrumentationRegistry

    Hi, I'm trying to add Barista to a brand new project, but I'm having this error.

    This is my dependencies block:

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
        implementation 'androidx.appcompat:appcompat:1.0.2'
        implementation 'androidx.core:core-ktx:1.0.1'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test.ext:junit:1.1.0'
        androidTestImplementation('com.schibsted.spain:barista:2.7.1') {
            exclude group: 'com.android.support'
            exclude group: 'org.jetbrains.kotlin' // Only if you already use Kotlin in your project
        }
    }
    

    I haven't coded anything in AndroidX before, but it seems like it could be a bug in Jetifier again, as in #268? I've tried to exclude the module with the InstrumentationRegistry class, both in Android Support and in AndroidX, with no success...

    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar'])
        implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
        implementation 'androidx.appcompat:appcompat:1.0.2'
        implementation 'androidx.core:core-ktx:1.0.1'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        testImplementation 'junit:junit:4.12'
        androidTestImplementation 'androidx.test.ext:junit:1.1.0'
        androidTestImplementation('com.schibsted.spain:barista:2.7.1') {
            exclude group: 'com.android.support'
            exclude group: 'org.jetbrains.kotlin' // Only if you already use Kotlin in your project
            exclude group: 'com.android.support.test', module: 'runner'
            exclude group: 'androidx.test', module: 'monitor'
        }
    }
    
    help wanted 
    opened by serandel 13
  • Introduce generic assertAnyView function

    Introduce generic assertAnyView function

    TL;DR:

    This method allows asserting that any view on the screen matches a certain condition, without getting the infamous Espresso error AmbiguousViewMatcherException.

    Rationale

    We say we do magic for things like views below a scroll or duplicated views on screen. But actually that only work for some Assertions and Interactions, not all of them implement it. E.g.: https://github.com/SchibstedSpain/Barista/issues/107 https://github.com/SchibstedSpain/Barista/issues/46

    Solution

    In this PR I propose to extract the assertion code to one place, and reuse it everywhere it's needed. (The same should be done for Interactions, see https://github.com/SchibstedSpain/Barista/pull/196). I created a function to be used like this:

    assertAnyView(withId(R.id.button), isDisplayed())
    

    We don't usually expose kotlin APIs, but since this method is intended for internal usage I also added an extension function alias:

    withId(R.id.button).assertAny(isDisplayed())
    
    review-please 
    opened by Sloy 13
  • Accept repeated views

    Accept repeated views

    This is a solution proposal for #37

    The trick is to combine firstViewOf() with allOf(), and include the verification as a condition. Yeah, that crazy. But it should work.

    opened by Sloy 13
  • Better IdlingResources

    Better IdlingResources

    It's just a suggestion to add

    Based on the old wait / timeout resource talk [241] (https://github.com/SchibstedSpain/Barista/issues/241)

    I created an Kotlin extension to wait any assert block with lambda function.Example espresso code if available

    fun BaristaVisibilityAssertions.assertTimeout(timeoutSeconds: Int, assert: () -> Unit) {
        val startTime = System.currentTimeMillis()
        val endTime = startTime + TimeUnit.MILLISECONDS.convert(timeoutSeconds.toLong(), TimeUnit.SECONDS)
    
        do {
            try {
                assert()
                break
            } catch (e: BaristaException) {
                //Not click
                BaristaSleepInteractions.sleep(1, TimeUnit.SECONDS)
            } catch (ae: AssertionFailedError) {
                //Not enable
                BaristaSleepInteractions.sleep(1, TimeUnit.SECONDS)
            }
    
        } while (System.currentTimeMillis() < endTime)
    
        // timeout happens
        if (System.currentTimeMillis() > endTime) {
            throw TimeoutException("TIMEOUT:wait for a specific view to click. Waiting during $timeoutSeconds seconds.")
        }
    }
    
    
    opened by diogosq 12
  • assertNotExist with viewmatcher

    assertNotExist with viewmatcher

    I have noticed there is not implementation of assertNotExist where the input parameters is a viewmatchers.

    Being able to specify a viewmatcher allow much more complexity in the assertion, for example asserting in a sub part of the view hierarchy if a text exist. It can be useful when working with view pager.

    opened by moutyque 0
  • Failed to resolve: androidx.test:core:1.5.0

    Failed to resolve: androidx.test:core:1.5.0

    Library Version:

    4.3.0

    Describe the Bug:

    Failed to resolve dependencies when trying to use Barista with test:*:1.5.0.

    This is the message output:

    Unresolved dependencies
    
    Cannot find a version of 'androidx.test:core' that satisfies the version constraints:
       Dependency path 'Flat:app:unspecified' --> 'androidx.test:core:1.5.0'
       Constraint path 'Flat:app:unspecified' --> 'androidx.test:core:{strictly 1.4.0}' because of the following reason: productionDebugRuntimeClasspath uses version 1.4.0
       Dependency path 'Flat:app:unspecified' --> 'androidx.test.ext:truth:1.5.0' (runtime) --> 'androidx.test:core:1.5.0'
       Dependency path 'Flat:app:unspecified' --> 'androidx.test.ext:junit-ktx:1.1.4' (runtime) --> 'androidx.test.ext:junit:1.1.4' (runtime) --> 'androidx.test:core:1.5.0'
       Dependency path 'Flat:app:unspecified' --> 'androidx.test.espresso:espresso-contrib:3.5.0' (runtime) --> 'androidx.test.espresso:espresso-core:3.5.0' (runtime) --> 'androidx.test:core:1.5.0'
       Dependency path 'Flat:app:unspecified' --> 'com.adevinta.android:barista:4.3.0' (releaseRuntimePublication) --> 'androidx.test.espresso:espresso-intents:3.4.0' (runtime) --> 'androidx.test:core:1.4.0'
    

    Steps to reproduce the bug: Have a build.gradle file with:

            testImplementation        'androidx.test:core:1.5.0'
            androidTestImplementation 'androidx.test:core:1.5.0' 
            testImplementation        'androidx.test:rules:1.5.0'
            androidTestImplementation 'androidx.test:rules:1.5.0' 
            testImplementation        'androidx.test.ext:truth:1.5.0' 
            androidTestImplementation 'androidx.test.ext:truth:1.5.0'
    

    Expected Behavior:

    Work with v1.5.0 of androidx.test libraries.

    opened by cdiazc 0
  • java.lang.SecurityException: Calling from not trusted UID! with 4.1.0 and + version

    java.lang.SecurityException: Calling from not trusted UID! with 4.1.0 and + version

    Library Version: 4.1.0 and 4.2.0

    Describe the Bug: After the project is successfully compiled, running tests fails on the first test case. The stack trace doesn't show a crash, but by digging through the stack trace, I found some usable things, mainly related to the issue mentioned in the title. Rolling the project back to 4.0.0 fixes the issue, and I can run tests properly. This issue is not device dependent on my side since tests fail on real devices and multiple emulators.

    Stacktrace

    1-08 19:29:05.865 18316 18329 W Binder  : Caught a RuntimeException from the binder stub implementation.
    11-08 19:29:05.865 18316 18329 W Binder  : java.lang.SecurityException: Calling from not trusted UID!
    11-08 19:29:05.865 18316 18329 W Binder  : 	at android.app.UiAutomationConnection.throwIfCalledByNotTrustedUidLocked(UiAutomationConnection.java:525)
    11-08 19:29:05.865 18316 18329 W Binder  : 	at android.app.UiAutomationConnection.shutdown(UiAutomationConnection.java:429)
    11-08 19:29:05.865 18316 18329 W Binder  : 	at android.app.IUiAutomationConnection$Stub.onTransact(IUiAutomationConnection.java:390)
    11-08 19:29:05.865 18316 18329 W Binder  : 	at android.os.Binder.execTransactInternal(Binder.java:1159)
    11-08 19:29:05.865 18316 18329 W Binder  : 	at android.os.Binder.execTransact(Binder.java:1123)
    
    opened by robertvargic 1
  • Snackbar action

    Snackbar action

    Hi! If I use real device:

    1. clickOn(com.google.android.material.R.id.snackbar_action)

    2. com.adevinta.android.barista.internal.failurehandler.BaristaException: Could not perform action single click on view view.getId() is <2131296660/com.*:id/snackbar_action>

    The snack bar has LENGTH_INDEFINITE

    opened by artests87 0
  • make `assertRecyclerViewItemCount` accept logical condition instead of exact number

    make `assertRecyclerViewItemCount` accept logical condition instead of exact number

    Description what you'd like to happen: cuurently we have assertRecyclerViewItemCount(id , num), what about have ability to be like assertRecyclerViewItemCount(id , num > 5 or ) and logical check

    opened by MahmoudMabrok 0
Releases(4.3.0)
  • 4.3.0(Nov 15, 2022)

    What's Changed

    • Remove the CI badge because the test environment is flaky by @rocboronat in https://github.com/AdevintaSpain/Barista/pull/445
    • Tech: Add api 31 to test by @alorma in https://github.com/AdevintaSpain/Barista/pull/447
    • Fix: API 31 run tests by @alorma in https://github.com/AdevintaSpain/Barista/pull/449
    • Update the company behind Barista by @rocboronat in https://github.com/AdevintaSpain/Barista/pull/453
    • Remove the CI badge from the readme by @rocboronat in https://github.com/AdevintaSpain/Barista/pull/452
    • Update README.md by @stavares843 in https://github.com/AdevintaSpain/Barista/pull/460
    • Feature: check checkbox by @SmasSive in https://github.com/AdevintaSpain/Barista/pull/465

    New Contributors

    • @stavares843 made their first contribution in https://github.com/AdevintaSpain/Barista/pull/460

    Full Changelog: https://github.com/AdevintaSpain/Barista/compare/4.2.0...4.3.0

    Source code(tar.gz)
    Source code(zip)
  • 4.1.0(Aug 31, 2021)

  • 4.0.0(Aug 19, 2021)

  • 3.10.0-sonatype(Aug 19, 2021)

  • v3.10.0(May 17, 2021)

  • v3.9.0(Mar 10, 2021)

  • v3.8.0(Mar 2, 2021)

  • v3.7.0(Oct 1, 2020)

    New:

    • Update PermissionGranter to allow android 11 permissions (#366)
    • Add ViewPager2 swipe support (#368)
    • Assert view background with a plain color (#371)

    Fixes:

    • Make FlakyRule tests less flaky (#362)

    Other changes:

    Source code(tar.gz)
    Source code(zip)
  • v3.6.0(Aug 19, 2020)

    New:

    • Day night rule (#359)

    Fixes:

    • Fixed visibility assertions (#316)
    • PermissionGranter should click foreground grant button for location (#356)
    • Update disabled states for color state list (#353)
    • Fix color state list color check (#351)

    Other changes:

    • Downgrade emulator version for better stability (#363)
    • Make DatabaseOperations class open with all its methods (#346)
    • Update emulator workflow (#361)
    • Simplify PermissionGranterTest (#360)
    • Entry point on github actions (#334)
    • Remove Jetifier (#350)
    • Add Sponsor button linking to our "Thank you" post (#349)
    • Move the assertions tricky feature to the end of the list (#348)
    • Change the .kotlin_module generated name (#347)
    Source code(tar.gz)
    Source code(zip)
  • v3.5.0(May 7, 2020)

  • v3.4.0(Apr 15, 2020)

  • v3.3.0(Apr 9, 2020)

    • Update color matcher to accept attribute colors and color int (#340)

    • Add test for vector image assertHasDrawable (#315)

    • Add open overflowMenu action (#332)

    • Add chips interactions and assertions (#321)

    • Add scrollTo() signatures to support scrolling on a custom view matcher (#323)

    • Removed exclude group: 'com.android.support' (#317)

    • Better explain how to mock the camera (#325)

    Source code(tar.gz)
    Source code(zip)
  • v3.2.0(Jul 30, 2019)

  • v3.1.0(Jun 6, 2019)

  • v3.0.0(May 21, 2019)

    Big change! We finally migrated from the Support Library to AndroidX. If you're using AndroidX already in your project, you should be safe to use Barista 3.0.0. Please report any issues you may find.

    • Migrate to AndroidX (#301)
    • Update Gradle and tools (#300)
    • Fix a typo in the reame
    • Issue templates (#291)
    • Add missing displayed examples (#290)
    Source code(tar.gz)
    Source code(zip)
  • v2.10.0(Mar 27, 2019)

  • v2.9.0(Mar 13, 2019)

    • Add RatingBar interaction support (#285)
    • Add BaristaClickableAssertions (#277)
    • Add new features in BaristaListAssertions (#280)
    • Separate API sample code into blocks (#282)
    Source code(tar.gz)
    Source code(zip)
  • v2.8.0(Feb 28, 2019)

    • Apply new code style to the whole project (#272)
    • Rename assertionErrorMessage to assertionDescription (#273)
    • Adds assertDisplayed(Matcher) and assertNotDisplayed(Matcher) methods (#271)
    • Add Schibsted code style (#270)
    Source code(tar.gz)
    Source code(zip)
  • v2.7.1(Dec 19, 2018)

    • Fix assertListItemCount not throwing error when failed bug (#269)
    • Made license file link working (#263)
    • Clarify how to use the custom assertions message (#257)
    • Improve the explanation about custom assertions (#255)
    • Rename custom assertion message parameter to better explain its intention (#256)
    Source code(tar.gz)
    Source code(zip)
  • v2.7.0(Feb 28, 2019)

  • v2.6.0(Feb 28, 2019)

    • Clear files with optional regex filter (#250)
    • Update write methods to work with wrapped EditTexts (#245)
    • Assert displayed with string resource (#247)
    • Safer view pager swipe actions (#243)
    Source code(tar.gz)
    Source code(zip)
  • v2.5.0(Jul 5, 2018)

    New:

    • Hint and error assertions (#236)
    • Added setTimeOnPicker function that populates the hour and minute on a time picker (#237)
    • Added clearText function for EditTexts (#238)

    Fixes:

    • Make public ActivityTestRule from BaristaRule (#215)
    • Fix ListInteractions failure handling (#240)
    • Improve assertion tests and errors (#242)

    Others:

    • Created ViewActionExecutor to reuse performAction() code (#194)
    • Explain how to use @get:Rule in Kotlin tests (#221)
    • Update libraries, build tools, gradle version, etc (#222)
    • Update readme with new Gradle syntax (#225)
    Source code(tar.gz)
    Source code(zip)
  • v2.4.0(Jul 5, 2018)

  • v2.3.0(Feb 1, 2018)

    • Fake camera calls intents (#159)

    • Better Kotlin support for BaristaRule (#205)

    • Remove barista2 branch for travis (#206)

    • Barista logo svg (#201)

    Source code(tar.gz)
    Source code(zip)
  • v2.2.0(Dec 19, 2017)

    • Fixes wrong error handling on assertDisplayed (#192)
    • Adding interactions for SeekBar views (#182)
    • Update readme look and feel (#191)
    • Add keyboard interactions (#185)
    • Fix the "not" section of the text color asserts (#190)
    • Add with text color (#179)
    • Create CODE_OF_CONDUCT.md (#189)
    • Added support for GridView interactions (#188)
    • Add assert not displayed with text (again) (#186)
    • Add assertContains matcher (#170)
    • Assert that a given View has a background, any background or no background (#174)
    • BaristaSpinnerInteractions converted to kotlin (#180)
    • Update readme (#177)
    Source code(tar.gz)
    Source code(zip)
  • v2.1.0(Nov 24, 2017)

    Don't know why, on Barista 2.0 we removed that feature. But you still need it, isn't it? So, he's back, like Terminator, but being a method of the Barista public API. #176

    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Nov 23, 2017)

    Yeeey! Check out the migration guide!

    • Improve error handling on magic methods (#134)
    • Change click to clickOn (#144)
    • Changed package structure (#143)
    • Add pull to refresh without id (#150)
    • Add focus assertions (#148)
    • Merge RecyclerView and ListView actions into ListActions (#146)
    • Create FlakyTestRule independent from ActivityTestRule (#160)
    • Rename and remove some APIs (#161)
    • Add assertText to check a given text is shown in a given view (#157)
    • Rename Barista Actions to Interactions (#162)
    • Split assertion classes (#171)
    Source code(tar.gz)
    Source code(zip)
  • v1.9.0(Nov 21, 2017)

  • v1.8.0(Nov 3, 2017)

Owner
Adevinta Spain
OpenSource Projects of Adevinta Spain
Adevinta Spain
A library that makes it easier to write high quality automated acceptance tests

Getting started with Serenity and Cucumber Serenity BDD is a library that makes it easier to write high quality automated acceptance tests, with power

ricardo larrahondo 1 Oct 20, 2021
Kotlin wrapper for React Test Renderer, which can be used to unit test React components in a Kotlin/JS project.

Kotlin API for React Test Renderer Kotlin wrapper for React Test Renderer, which can be used to unit test React components in a Kotlin/JS project. How

Xavier Cho 7 Jun 8, 2022
Toster - Small test dsl based on adb commands that allows you to test the mobile application close to user actions

toster Small test dsl based on adb commands that allows you to test the mobile a

Alexander Kulikovskiy 31 Sep 1, 2022
Lbc-test-app - Test Android Senior Leboncoin

Test Android Senior Leboncoin ?? Mathieu EDET Overview Min API version : 24 This

null 0 Feb 7, 2022
Powerful, elegant and flexible test framework for Kotlin with additional assertions, property testing and data driven testing

Kotest is a flexible and comprehensive testing tool for Kotlin with multiplatform support. To learn more about Kotest, visit kotest.io or see our quic

Kotest 3.8k Jan 3, 2023
null 866 Dec 27, 2022
TestObserver to easily test LiveData and make assertions on them.

JCenter Update LiveData Testing is currently published on JCenter - it will serve packages until February 1st, 2022. LiveData Testing packages will be

Josef Raska 395 Dec 8, 2022
A program to calculate the distance traveled during the run the calories burned and the average speed Display data in more than one way using a graph

Running App Features: A program to calculate the distance traveled during the run the calories burned and the average speed Display data in more than

mostafa elmorshdi 1 Nov 21, 2022
PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

Writing unit tests can be hard and sometimes good design has to be sacrificed for the sole purpose of testability. Often testability corresponds to go

PowerMock 3.9k Jan 5, 2023
A powerful test framework for Android

Cafe A powerful test framework for Android named Case Automated Framework for Everyone. Home Page http://baiduqa.github.com/Cafe/ How to make Cafe dow

Baidu 367 Nov 22, 2022
A custom instrumentation test runner for Android that generates XML reports for integration with other tools.

Android JUnit Report Test Runner Introduction The Android JUnit report test runner is a custom instrumentation test runner for Android that creates XM

Jason Sankey 148 Nov 25, 2022
A powerful test framework for Android

Cafe A powerful test framework for Android named Case Automated Framework for Everyone. Home Page http://baiduqa.github.com/Cafe/ How to make Cafe dow

Baidu 367 Nov 22, 2022
PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

Writing unit tests can be hard and sometimes good design has to be sacrificed for the sole purpose of testability. Often testability corresponds to go

PowerMock 3.9k Jan 2, 2023
Linkester is an Android library that aims to help Android developers test their deep links implementation.

Linkester Linkester is an Android library that aims to help Android developers test their deep links implementation. The idea is to have a new launche

Ahmad Melegy 79 Dec 9, 2022
Strikt is an assertion library for Kotlin intended for use with a test runner such as JUnit, Minutest, Spek, or KotlinTest.

Strikt is an assertion library for Kotlin intended for use with a test runner such as JUnit, Minutest, Spek, or KotlinTest.

Rob Fletcher 447 Dec 26, 2022
Easily scale your Android Instrumentation Tests across Firebase Test Lab with Flank.

Easily scale your Android Instrumentation Tests across Firebase Test Lab with Flank.

Nelson Osacky 220 Nov 29, 2022
The coding challenge elbotola android test

Introduction The coding challenge(s) below will be used to assess your familiarity with the Android development environment, relevant Android related

Mohamed Elouamghari 1 Nov 2, 2021
Android background tint test project

Android Background Tint References https://developer.android.com/reference/android/view/View#attr_android:background https://developer.android.com/ref

Ashwin Dinesh 0 Nov 4, 2021
Test for openbank application

openbank-test Test for openbank application Here you can find a simple test for the OpenBank application. It fetches some characters from the Marvel A

anon37894203 0 Nov 3, 2021