2013-08-02 10 views
8

Sto scrivendo un test di unità Robolectric e ho bisogno di fare una asserzione che un ImageView aveva setImageResource(int) chiamato su di esso con un certo ID di risorsa. Sto usando fest-android per asserzioni ma non sembra contenere questa asserzione.Assert ImageView è stato caricato con un ID risorsa estraibile specifico

Ho anche provato a ottenere il ShadowImageView da Robolectric per l'ImageView perché so che era solito permettervi di accedere a questo, ma ora non c'è più.

Infine, ho provato a chiamare setImageDrawable nel mio codice, invece di setImageResource, poi nel mio test affermare in questo modo:

assertThat(imageView).hasDrawable(resources.getDrawable(R.drawable.some_drawable)); 

, ma anche questo non funziona, anche se il messaggio di errore mostra chiaramente che è lo stesso essere Drawable caricato.

risposta

5

ho finito per estendere fest-Android per risolvere questo:

public class CustomImageViewAssert extends ImageViewAssert { 

    protected CustomImageViewAssert(ImageView actual) { 
     super(actual); 
    } 

    public CustomImageViewAssert hasDrawableWithId(int resId) { 
     boolean hasDrawable = hasDrawableResourceId(actual.getDrawable(), resId); 
     String errorMessage = String.format("Expected ImageView to have drawable with id <%d>", resId); 
     Assertions.assertThat(hasDrawable).overridingErrorMessage(errorMessage).isTrue(); 
     return this; 
    } 

    private static boolean hasDrawableResourceId(Drawable drawable, int expectedResId) { 
     BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; 
     Bitmap bitmap = bitmapDrawable.getBitmap(); 
     ShadowBitmap shadowBitmap = (ShadowBitmap) shadowOf(bitmap); 
     int loadedFromResourceId = shadowBitmap.getCreatedFromResId(); 
     return expectedResId == loadedFromResourceId; 
    } 
} 

La salsa è magia:

ShadowBitmap shadowBitmap = (ShadowBitmap) shadowOf(bitmap); 
int loadedFromResourceId = shadowBitmap.getCreatedFromResId(); 

che è Robolectric specifica, quindi non posso presentare una richiesta di pull a fest -android con questo.

23

Con Robolectric 2,2:

Bisogna prendere un leggero indirezione per raggiungere questo obiettivo. ShadowImageView non aiuta. Uso ShadowDrawable invece:

ImageView imageView = (ImageView) activity.findViewById(R.id.imageview); 
ShadowDrawable shadowDrawable = Robolectric.shadowOf(imageView.getDrawable()); 
assertEquals(R.drawable.expected, shadowDrawable.getCreatedFromResId()); 

Speranza che aiuta

+0

funziona come un fascino –

+2

In robolectric 2,4 il metodo è 'getImageResourceId()' – danielcooperxyz

6

Da Roboelectric 3.0+

Ecco come si può fare:

int drawableResId = Shadows.shadowOf(errorImageView.getDrawable()).getCreatedFromResId(); 
assertThat("error image drawable", R.drawable.ic_sentiment_dissatisfied_white_144dp, is(equalTo(drawableResId))); 
Problemi correlati