Android [intermediate tutorial] Chapter 4 unit test AndroidTestCase

Source: Internet
Author: User

I believe that many of you will feel inconvenient to operate SQLite, and you cannot clearly see the problem in database operations. Here we will take the SQLite operation helper class in the previous chapter for unit testing. OK, let's take a look at the class code: DatabaseHelper. java

 

 

Import android. content. Context;

Import android. database. sqlite. SQLiteDatabase;

Import android. database. sqlite. SQLiteOpenHelper;

 

Public class DatabaseHelper extends SQLiteOpenHelper

{

// Database Name

Private static final String DB_NAME = "SQLiteDemo. db ";

// Database version

Private static final int DB_VERSION = 1;

// Table name

Public static final String TABLE_NAME = "demo ";

Private static final String DB_CREATE = "create table" + TABLE_NAME + "(_ id integer primary key autoincrement, name varchar (20), number varchar (10 ))";

 

Public DatabaseHelper (Context context)

{

Super (context, DB_NAME, null, DB_VERSION );

}

/**

* Create a table

*/

@ Override

Public void onCreate (SQLiteDatabase db)

{

Db.exe cSQL (DB_CREATE );

 

}

 

/**

* Update a table

*/

@ Override

Public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)

{

// Db.exe cSQL ("drop table if exists" + TABLE_NAME );

// OnCreate (db );

 

}

 

}

Next, go to the data operation auxiliary class DatabaseServer. java

 

 

Import android. content. ContentValues;

Import android. content. Context;

Import android. database. Cursor;

Import android. database. sqlite. SQLiteDatabase;

 

Public class DatabaseServer

{

Private DatabaseHelper dbHelper;

 

Public DatabaseServer (Context context)

{

This. dbHelper = new DatabaseHelper (context );

}

 

/**

* Insert data

*

* @ Param name

* Name

* @ Param number

* Data

* @ Return returns true if the call succeeds. Otherwise, false is returned.

*/

Public boolean insert (String name, String number)

{

// Create or open a database

SQLiteDatabase db = dbHelper. getWritableDatabase ();

ContentValues cv = new ContentValues ();

Cv. put ("name", name );

Cv. put ("number", number );

// Insert data. The ID of the inserted data is returned.

Long id = db. insert (dbHelper. TABLE_NAME, null, cv );

If (id! = 0)

{

Return true;

}

 

Return false;

}

 

/**

* Update data

*

* @ Param id

* Data column _ id

* @ Param number

* Quantity

* @ Return returns true if the call succeeds. Otherwise, false is returned.

*/

Public boolean update (int id, String number)

{

 

SQLiteDatabase db = dbHelper. getWritableDatabase ();

// Android built-in ContetValues, similar to Map, provides the put (String key, XXX value) method to store data

ContentValues cv = new ContentValues ();

Cv. put ("number", number );

// Update the data table through ContentValues and return the updated ID value

Int result = db. update (dbHelper. TABLE_NAME, cv, "_ id =? ",

New String [] {String. valueOf (id )});

 

If (result! = 0)

{

Return true;

}

 

Return false;

}

 

/**

* Delete data

*

* @ Param id

* Data column _ id

* @ Return

*/

Public boolean delete (int id)

{

 

SQLiteDatabase db = dbHelper. getWritableDatabase ();

// Delete the specified ID value

Int result = db. delete (dbHelper. TABLE_NAME, "_ id =? ",

New String [] {String. valueOf (id )});

 

If (result! = 0)

{

Return true;

}

 

Return false;

}

 

/**

* Query data

*

* @ Return returns the data list.

*/

Public Cursor fetchAll ()

{

 

SQLiteDatabase db = dbHelper. getReadableDatabase ();

// Query all fields in the data table

Cursor cursor = db. query (dbHelper. TABLE_NAME, null,

Null, "_ id desc ");

If (cursor! = Null)

{

Return cursor;

}

Return null;

 

}

}

Both classes have been created, but we need to test whether the two classes we created work normally, whether they can be inserted, updated, deleted, or queried. Here we use TestCase for testing.

 

SQLiteDemoTest. java

 

 

Import android. database. Cursor;

Import android. test. AndroidTestCase;

 

Public class SQLiteDemoTest extends AndroidTestCase

{

Private DatabaseServer dbServer;

/**

* Test data insertion

*/

Public void testinsert ()

{

DbServer = new DatabaseServer (this. getContext ());

Boolean flag = dbServer. insert ("sashan", "10 ");

System. out. println (flag );

}

/**

* Test Data Query

*/

Public void testfetchAll ()

{

DbServer = new DatabaseServer (this. getContext ());

Cursor cursor = dbServer. fetchAll ();

While (cursor. moveToNext ())

{

System. out. println (cursor. getString (1 ));

System. out. println (cursor. getString (2 ));

}

 

}

/**

* Test and update data

*/

Public void testupdate ()

{

DbServer = new DatabaseServer (this. getContext ());

Boolean flag = dbServer. update (1, "20 ");

System. out. println (flag );

}

/**

* Test data deletion

*/

Public void testdelete ()

{

DbServer = new DatabaseServer (this. getContext ());

Boolean flag = dbServer. delete (1 );

System. out. println (flag );

}

}

Of course, do not forget to add the Test Library file to AndroidManifest. xml.

 

 

<? Xml version = "1.0" encoding = "UTF-8"?>

<Manifest xmlns: android = "http://schemas.android.com/apk/res/android"

Package = "com. kang. button_demo" android: versionCode = "1"

Android: versionName = "1.0" type = "codeph" text = "/codeph">

<Uses-sdk android: minSdkVersion = "10"/>

 

<Application android: icon = "@ drawable/icon" android: label = "@ string/app_name">

<Uses-library android: name = "android. test. runner"/>

<Activity android: label = "@ string/app_name" android: name = ". SQLiteDemo">

<Intent-filter>

<Action android: name = "android. intent. action. MAIN"/>

<Category android: name = "android. intent. category. LAUNCHER"/>

</Intent-filter>

</Activity>

 

</Application>

 

<Instrumentation android: name = "android. test. InstrumentationTestRunner"

Android: targetPackage = "com. kang. button_demo" android: label = "Tests for My App"/>

</Manifest>

Here is a <uses-library> test library, which must be added, and <instrumentation android: name = "android. test. InstrumentationTestRunner"

Android: targetPackage = "com. kang. button_demo "android: label =" Tests for My App "/> must also be added. This is the test package. Your test file must be placed under the root package, here, my root package is com. kang. button_demo

Okay, you can run it to see if blue bars appear, instead of red bars,

From: kangkangz4 Column

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.