Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Robolectric RoboAttributeSet - How to use this

I have a custom android view with styleable attributes that I'd like to test. I'm trying to use RoboAttributeSet to push these into the constructor of my view, but for the life of me can't work out the correct syntax I need to use to get them working. No matter what I try, the attributes that I'm pushing in are not picked up by the view when running within a robolectric test. Running the app on device or emulator is fine.

Are there any examples of how one might use these? Does anyone know how to do this? Here is a code snippet of my custom view and how it uses styleable attributes.

TypedArray customProperties = aContext.getTheme().obtainStyledAttributes(aAttrs, R.styleable.LoginView, 0, 0);

try {
  userName.setHint(customProperties.getString(R.styleable.LoginView_username_hint));
} finally {
  customProperties.recycle();
}

Here is a snippet from my Robolectric/Spock unit test...

given:
AttributeSet attributes = new RoboAttributeSet(
        [new Attribute("com.acme:attr/username_hint", "myhint", "com.acme")], Robolectric.application.resources, LoginView)

when:
view = new LoginView(Robolectric.application, attributes)

then:
view.getUsername().getHint() == "myhint"

Thanks
George

like image 387
George Papas Avatar asked Nov 13 '13 05:11

George Papas


1 Answers

For those that are using the new version 3 of RoboElectric check out this sample from their github on how to use the ResourceLoader.

https://github.com/robolectric/robolectric/blob/490e5fcb7165bec9ef2ddc1c937af790806bb13d/robolectric/src/test/java/org/robolectric/shadows/ViewStubTest.java#L59

Took me way to long to find an example like this!

Edit:

I just wanted to update this thread since a lot of things have changed over the past year. Google has somewhat provided a means of official documenation around testing with Android. You can find it

here: https://google.github.io/android-testing-support-library/

& here: https://github.com/googlesamples/android-testing

like image 184
John Shelley Avatar answered Oct 01 '22 12:10

John Shelley