Showing posts with label Junit. Show all posts
Showing posts with label Junit. Show all posts

Tuesday, June 11, 2013

Android: Unit Test for Custom Content Provider using Roboelectric



Robolectric provides a simple approach to automate unit test case for android by using standard JUnit tests. It runs on any JVM, without needing the emulator or a device.
Advantages of Roboelectric:
No Mocking Frameworks Required

Run Tests Outside of the Emulator

Test Annotations

@RunWith

To run your test with Robolectric, you need to tell JUnit using the @RunWith annotation on your test class:
@RunWith (RobolectricTestRunner.class) // required for Robolectric!
For more details: http://pivotal.github.io/robolectric/user-guide.html
With Robolectric, we can write a small unit test for custom content provide like this.

@RunWith(RobolectricTestRunner.class)
public class BookContentProviderTest {

 private Activity activity;
 private BookProvider bookProvider;
 private ContentResolver contentResolver;

 public static final String AUTHORITY = "com.test.provider.Book";

 public static final String BOOK_TABLE_NAME = "book";

 /**
  * The columns we are interested in from the database
  */
 public static final String[] BOOK_PROJECTION = new String[] {
   BookColumns._ID, // 0
   BookColumns.BOOK_NAME, // 1
 };

 public static final Uri BOOK_URI = Uri.parse("content://" + AUTHORITY + "/"
   + BOOK_TABLE_NAME);

 private String[] bookList = new String[] { "angels and demons", "Book1",
   "Book2", "Book3" };

 @Before
 public void setUp() throws Exception {
  bookProvider = new BookProvider();
  activity = new Activity();
  contentResolver = activity.getContentResolver();

  bookProvider.onCreate();
  ShadowContentResolver.registerProvider(AUTHORITY, bookProvider);
 }

 @Test
 public void testContentProvider() {

  insertBook(new Book("53bfc0b980b0", "angels and demons"));
  insertBook(new Book("53bfc0b980b3", "Book1"));
  insertBook(new Book("53bfc0b980b1", "Book2"));
  insertBook(new Book("53bfc0b980b2", "Book3"));

  Cursor cursor = contentResolver.query(BOOK_URI, BOOK_PROJECTION, null,
    null, BookColumns.DEFAULT_SORT_ORDER);

  cursor.moveToFirst();

  Assert.assertTrue(cursor.getCount() == 4);

  if (cursor.getCount() != 0) {
   do {
    Assert.assertEquals(bookList[cursor.getPosition()],
      cursor.getString(cursor
        .getColumnIndex(BookColumns.BOOK_NAME)));
   } while (cursor.moveToNext());
  }

 }

 private void insertBook(Book book) {
  contentResolver.insert(BOOK_URI, getContentValue(book));
 }

 private ContentValues getContentValue(Book book) {
  ContentValues values;
  values = new ContentValues();
  values.put(BookColumns._ID, book.getBookId());
  values.put(BookColumns.BOOK_NAME, book.getName());
  return values;
 }
}

Tuesday, August 30, 2011

Ant script for JUnit

Ant script is build to test the JUnit test framework. Before creating any test case we need Java compiler, Ant and JUnit.
we need junit.jar in your Ant's library folder or have jar file in our project lib folder.

Sample JUnit Test class to fecth records.

import junit.framework.TestCase;
public class EmpTest extends TestCase {
    /**
     * fetch records based on Employee ID from Employee table.
     */
    public final void testFetchByID() {
        Integer empId = 2;
        EmpTO empTO = empDAO.findById(empId);

        System.out.println("Fetch Employee ID " + empId
                + ", FirstName : " + empTO.getFirstName());
    }
}

Build.xml for JUnit

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="test">

    <!-- Source and class folders used in project-->
    <property name="testdir" location="bin" />
    <property name="srcdir" location="source" />
    <property name="srctestdir" location="source-test" />

    <!-- consists of destination class files and jar files from lib folder-->
    <path id="test.classpath">
        <pathelement location="${testdir}" />
        <fileset dir="${basedir}/lib">
            <include name="**/*.jar" />
        </fileset>
    </path>

    <!-- Delete all the class files from project -->
    <target name="clean">
        <delete>
            <fileset dir="${testdir}" includes="**/*.class" />
        </delete>
    </target>
   
    <!-- compiled source folder of project -->
    <target name="compile" depends="clean">
        <javac srcdir="${srcdir}" destdir="${testdir}">
            <classpath refid="test.classpath" />
        </javac>
        <javac srcdir="${srctestdir}" destdir="${testdir}">
            <classpath refid="test.classpath" />
        </javac>
    </target>
   
    <!-- Testing JUnit code by junit task -->
    <target name="test" depends="compile">   
       
        <junit printsummary="yes" haltonfailure="yes" showoutput="yes">
            <classpath refid="test.classpath" />
           
            <!-- The results of the tests can be printed in different formats.
            Output will always be sent to a file, unless you set the usefile attribute to false.
            The formatter named brief will only print detailed information for testcases that failed -->
           
            <formatter type="brief" usefile="false" />
           
            <!-- Define a number of tests based on pattern matching.
            fork      Run the tests in a separate VM.
            -->
            <batchtest fork="yes">
                <fileset dir="${basedir}/source-test/">
                    <include name="**/*Test.java" />
                </fileset>
            </batchtest>
        </junit>
    </target>
</project>

Output of xml file mostly look like this

Buildfile: E:\workspace\Project\EmployeeRecordProj\build.xml
clean:
compile:
    [javac] Compiling 6 source files to E:\workspace\Project\PROJECT_NAME\bin
test:
    [junit] Running com.test.EmpTest
    [junit] Testsuite: com.test.EmpTest
    [junit] Fetch Employee ID 2, FirstName : Harsha
    [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 1.61 sec
    [junit] Tests run: 1, Failures: 0, Errors: 0, Time elapsed: 1.61 sec
    [junit] ------------- Standard Output ---------------
    [junit] Fetch Employee ID 2, FirstName : Harsha
    [junit] ------------- ---------------- ---------------
    [junit] ------------- Standard Error -----------------
    [junit] ------------- ---------------- ---------------
BUILD SUCCESSFUL
Total time: 3 seconds