(单元)ArrayAdapter的测试 [英] (Unit)Testing of ArrayAdapter
问题描述
我在我的应用中广泛使用了 ArrayAdapter
大多数活动都持有 ListView
,我需要一些自定义里面的东西.
I have extensive use of ArrayAdapter
in my app because most Activities are holding a ListView
and I need some custom stuff in them.
我查看了android开发人员文档中的测试类,但找不到一些示例或适当的测试类...
I took a look at the test classes in the android developer documentation but wasn't able to find some examples or a proper testclass...
1)在Android中进行(单元)测试ArrayAdapter
是否有最佳实践?
1) Are there any best practices for (unit)-testing ArrayAdapter
in Android?
2)我可以选择错误的方法(使用适配器)并以这种方式终止可测试性吗?
2) May I have chosen the wrong approach (with the adapters) and killed testability this way?
推荐答案
您可以编写扩展测试AndroidTestCase
,它看起来像这样:
You can write the test extending AndroidTestCase
It will looks something like this:
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());
}
}
可能您必须使用不同的参数多次测试getView
,才能测试所有场景.
Probably you will have to test getView
several times with different arguments, to test all scenarios.
这篇关于(单元)ArrayAdapter的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!