gpt4 book ai didi

android - (Unit)ArrayAdapter的测试

转载 作者:IT老高 更新时间:2023-10-28 23:10:40 24 4
gpt4 key购买 nike

我广泛使用了ArrayAdapter在我的应用程序中,因为大多数 Activity 都持有 ListView我需要一些自定义的东西。

我查看了 android 开发人员文档中的测试类,但找不到一些示例或合适的测试类...

1) 有没有在 Android 中(单元)测试 ArrayAdapter 的最佳实践?

2) 我是否选择了错误的方法(使用适配器)并以这种方式杀死了可测试性?

最佳答案

您可以编写扩展 AndroidTestCase 的测试,它看起来像这样:

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 以测试所有场景。

关于android - (Unit)ArrayAdapter的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11541114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com