Create a gist now

Instantly share code, notes, and snippets.

Progressbar that is testable with Espresso

Create the main Progressbar wrapper in your main source code. Use it instead of the android.widget.Progressbar as it will just forward all calls to the default Progressbar.

In your androidTest package create the Progressbar class in the exact same package as you did in the main source code. This way all your UI tests will call this ProgressBar instead of the default one. And since the modifications prevent the Progressbar from showing and animating, the UI thread won't be blocked and Espresso can continue the test.

/**
* Progressbar that is used in UI Tests
* Prevents the progressbar from ever showing and animating
* Thus allowing Espresso to continue with tests and Espresso won't be blocked
*/
public class ProgressBar extends android.widget.ProgressBar {
public ProgressBar(Context context) {
super(context);
setUpView();
}
public ProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
setUpView();
}
public ProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setUpView();
}
private void setUpView() {
this.setVisibility(GONE);
}
@Override
public void setVisibility(int v) {
// Progressbar should never show
v = GONE;
super.setVisibility(v);
}
@Override
public void startAnimation(Animation animation) {
// Do nothing in test cases, to not block ui thread
}
}
/**
* Progressbar that just calls the default implementation of Progressbar
* Should always be used instead of {@link android.widget.ProgressBar}
*/
public class ProgressBar extends android.widget.ProgressBar {
public ProgressBar(Context context) {
super(context);
}
public ProgressBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
@amostyaev

Many thanks!

@RafaO
RafaO commented Mar 7, 2016

Don't you get a duplicate class error?

@alarikmyrin

Thank you for this! It works like a charm. And so ends a 24 hour period of pulling my hair out. I just can't figure out how to suppress the warning about the duplicate classes from Android Studio.

@Maragues

Thanks!

Just don't create this progressbar in android.widget package and attempt to name it ProgressBar, since it will collide with the real ProgressBar and you won't be able to override the methods.

@githubandrewd

I am getting duplicate class error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment