Android Unit Testing

Alex Egg,

Android testing is like this: You have your android app projection. Then you have your android app test project which is another android app! When you run your tests ant run-tests it build and installs your app and then builds and installs your test app and then runs the test - SUPER SLOW.

This is my setup to use android unit tests w/ ant:

I have this directory structure:
src/com.asdf/
src/com.asdf/AllTests.java
src/com.asdf/MyClassTests.java
src/com.asdf/MyOtherClassTests.java
src/com.asdf/MyActivityTests.java
src/com.asdf/…

So then when you run ant run-tests it will pick up all those tests b/c of AllTests.java

AllTests.java:

package com.asdf;

import junit.framework.Test;
import junit.framework.TestSuite;

import android.test.suitebuilder.TestSuiteBuilder;


public class AllTests extends TestSuite {

    public static Test suite() {
        return new TestSuiteBuilder(AllTests.class)
                .includeAllPackagesUnderHere()
                .build();
    }
}

Have you other tests inherit from InstrumentationTestCase so that you can call getContext() and getInstrumentation() to get the context of your actual app and your test app respectively. Then you can call getAssets() etc…

package com.asdf;
import static org.junit.Assert.*;
import junit.framework.JUnit4TestAdapter;
import org.junit.Before;
import org.junit.After;
import org.junit.Test;
import org.apache.http.HttpResponse;
import java.io.File;
import java.net.URI;
import java.io.*;
import junit.framework.TestCase;
import android.test.suitebuilder.annotation.SmallTest;
import android.os.Environment;
import android.test.AndroidTestCase;
import android.util.Log;
import android.test.ActivityTestCase;
import android.content.res.AssetManager;
import android.test.InstrumentationTestCase;
import android.content.Context;


public class MyClassTests extends InstrumentationTestCase
{
	protected String cache_dir=Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/com.asdf.MyClassTest/"+"test/cache/";
	protected AssetManager assets_ref;
	

	@Override
    protected void setUp() throws Exception {
        super.setUp();	
		//recreate cache
		(new File(cache_dir)).mkdir();
		
		assets_ref= getInstrumentation().getContext().getAssets();
    }
...
.
.
.

Permalink: android-unit-testing

Tags:

Last edited by Alex Egg, 2016-10-05 19:00:51
View Revision History