我使用JUnit
測試我的android應用程序。這是我第一次測試JUnit
,所以我不知道我應該遵循的路徑。現在我正在測試查詢到聯繫人列表。許多方法僅需要Raw Contact ID
或Contact ID
作爲參數,其中大多數方法或者返回JSON Object
,JSON Array
或ArrayList
。JUnit測試 - 最好和最可靠的方式來做我的測試?
我的問題是,我應該如何比較我的預期結果和實際結果?
現在我這樣的測試他們:
public void testGetRelationship() {
JSONArray jsonArrayActual = new JSONArray();
JSONArray jsonArrayExpected = new JSONArray();
try {
jsonArrayExpected = contact.getRelationship(RAW_CONTACT_ID);
} catch (JSONException e) {
e.printStackTrace();
fail("Failed when calling the getRelationship method. " + e.getMessage());
}
Cursor cursor = getContext().getContentResolver().query(Data.CONTENT_URI,
new String[]{Relation.NAME, Relation.TYPE, Relation._ID, Relation.LABEL},
Relation.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?",
new String[]{RAW_CONTACT_ID, Relation.CONTENT_ITEM_TYPE},
null);
if(cursor.moveToFirst())
{
do{
try {
final JSONObject jsonRelationshipObject = new JSONObject();
final String name = cursor.getString(0);
final Integer type = cursor.getInt(1);
final Integer id = cursor.getInt(2);
final String label = cursor.getString(3);
jsonRelationshipObject.put("id", id);
jsonRelationshipObject.put("type", type);
jsonRelationshipObject.put("label", label);
jsonRelationshipObject.put("name", name);
jsonArrayActual.put(jsonRelationshipObject);
} catch (JSONException e) {
e.printStackTrace();
fail("Failed while adding the values to the JSONObject. " + e.getMessage());
}
} while(cursor.moveToNext());
}
else
{
cursor.close();
fail("RawContact not found! ID: " + RAW_CONTACT_ID);
}
cursor.close();
try {
JSONAssert.assertEquals(jsonArrayExpected, jsonArrayActual, true);
} catch (JSONException e) {
e.printStackTrace();
cursor.close();
fail("JSONAssert exception: " + e.getMessage());
}
}
基本上我打電話給我的真正的方法和幾乎重新編碼我(測試)方法。我發現這是無用的,或者至少非常無聊和乏味(再次編碼我之前編寫的代碼)。我很確定有更好的方法來執行JUnit
測試。我想過我自己查詢聯繫人列表數據庫和手工建立我的對象進行比較,這樣的事情:
public void testGetRelationship() {
JSONArray jsonArrayActual = new JSONArray();
JSONArray jsonArrayExpected = new JSONArray();
try {
jsonArrayExpected = contact.getRelationship(RAW_CONTACT_ID);
} catch (JSONException e) {
e.printStackTrace();
fail("Failed when calling the getRelationship method. " + e.getMessage());
}
jsonRelationshipObject.put("id", 6);
jsonRelationshipObject.put("type", 1);
jsonRelationshipObject.put("label", "A label");
jsonRelationshipObject.put("name", "the name");
jsonArrayActual.put(jsonRelationshipObject);
try {
JSONAssert.assertEquals(jsonArrayExpected, jsonArrayActual, true);
} catch (JSONException e) {
e.printStackTrace();
cursor.close();
fail("JSONAssert exception: " + e.getMessage());
}
}
這是更快的代碼,但拉回就是我需要手動從手機下載數據庫(未對我來說是一個大問題),並手動查詢它以獲取數據(不是很重要),但它不是非常通用的,如果數據庫發生變化,我猜所有的測試都會失敗。但是我可以獲取數據庫的快照並保存,然後始終在該快照上執行測試。
有什麼建議嗎?改進?
什麼是junit版本? –
@PeterRader我正在使用版本3. – dazito