TouchScreen Testing 101

Posted: August 19, 2009 in Android, Java, Mobile
Tags: , , , ,

So you this nice android application but you need  to test the UI using some touch screen touch events in which you the developer supply the x and y coords in you test class. Right now there is not a TouchUtils method for this set of use cases. The method I came up with probably looks like this:

/**
*
* @param test
* @param view
* @param touchX in DIPs
* @param touchY in DIPs
*/
static void touchPoint(InstrumentationTestCase test, View view, float touchX, float touchY, Activity activity ) {

Instrumentation inst = test.getInstrumentation();
float screenDensity;
float screenWidthPx;
float screenHeightPx;
float touchTempX;
float touchTempY;
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis();

/**
* 1 dip = 1 pixel thus
* dip x density = pixels
*
* density of 1 equals
* 160 dpi 240×320 baseline display or 1.5″x2″
*/
DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
screenDensity = dm.density;
screenHeightPx = dm.heightPixels;
screenWidthPx = dm.widthPixels;

if (touchX * screenDensity <= screenWidthPx){ touchTempX = touchX * screenDensity; }else{ touchTempX = 1; } if (touchY * screenDensity <= screenHeightPx) { touchTempY = touchY *screenDensity; }else{ touchTempY = 1; } // touch down MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, touchTempX, touchTempY, 0); inst.sendPointerSync(event); inst.waitForIdleSync(); // touch up MotionEvent eventUp = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, touchTempX, touchTempY, 0); inst.sendPointerSync(eventUp); inst.waitForIdleSync(); } [/sourcecode] It should work. notice that it defaults to coords of 1,1 if you the developer goof up on your x and y cordinate inputs as its expected that you input your x and Y coordinates in terms of DIP not pixels so that your unit tests will always work no mater what the screen size.

Reblog this post [with Zemanta]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s