2012-07-18 19 views
19

Ho un ampio uso di ArrayAdapter nella mia app perché la maggior parte delle attività sono in possesso di un ListView e ho bisogno di alcune cose personali in loro.(unità) Test di ArrayAdapter

ho preso uno sguardo alle classi di test nella documentazione per gli sviluppatori Android, ma non è stato in grado di trovare alcuni esempi o un testclass corretta ...

1) Ci sono le migliori pratiche per (unità) -testing ArrayAdapter in Android?

2) Posso aver scelto l'approccio sbagliato (con gli adattatori) e ucciso la testabilità in questo modo?

risposta

31

È possibile scrivere il test si estende AndroidTestCase Sarà simile a questa:

public class ContactsAdapterTest extends AndroidTestCase { 
    private ContactsAdapter mAdapter; 

    private Contact mJohn; 
    private Contact mJane; 

    public ContactsAdapterTest() { 
     super(); 
    } 

    protected void setUp() throws Exception { 
     super.setUp(); 
     ArrayList<Contact> data = new ArrayList<Contact>(); 

     mJohn = new Contact("John", "+34123456789", "uri"); 
     mJane = new Contact("Jane", "+34111222333", "uri"); 
     data.add(mJohn); 
     data.add(mJane); 
     mAdapter = new ContactsAdapter(getContext(), data); 
    } 


    public void testGetItem() { 
     assertEquals("John was expected.", mJohn.getName(), 
       ((Contact) mAdapter.getItem(0)).getName()); 
    } 

    public void testGetItemId() { 
     assertEquals("Wrong ID.", 0, mAdapter.getItemId(0)); 
    } 

    public void testGetCount() { 
     assertEquals("Contacts amount incorrect.", 2, mAdapter.getCount()); 
    } 

    // I have 3 views on my adapter, name, number and photo 
    public void testGetView() { 
     View view = mAdapter.getView(0, null, null); 

     TextView name = (TextView) view 
       .findViewById(R.id.text_contact_name); 

     TextView number = (TextView) view 
       .findViewById(R.id.text_contact_number); 

     ImageView photo = (ImageView) view 
       .findViewById(R.id.image_contact_photo); 

     //On this part you will have to test it with your own views/data 
     assertNotNull("View is null. ", view); 
     assertNotNull("Name TextView is null. ", name); 
     assertNotNull("Number TextView is null. ", number); 
     assertNotNull("Photo ImageView is null. ", photo); 

     assertEquals("Names doesn't match.", mJohn.getName(), name.getText()); 
     assertEquals("Numbers doesn't match.", mJohn.getNumber(), 
       number.getText()); 
    } 
} 

Probabilmente si dovrà testare getView più volte con argomenti diversi, per testare tutti gli scenari.

+0

Funziona perfettamente. Grazie!! :) – eftokay83