2

I created a simple Android app (HelloWorld like) an dnow I would add operation to save sample data with mockdao (just a List to manage data). In future, I would persist data in sqlite db.

In Android project I created a simple object structure (a Task) and TaskService to manage list of task.

Now I want to create a junit test. I read that's better to create a new project (Android Test Project). I tried to create a simple android test project and adding my project to this test project. I created a first junit test based on the mockdao but whn I run the project I received this error :

java.lang.ClassNotFoundException: my.package.TaskServiceTest

In my android test project, junit test is in src/my.package.TaskServiceTest

In eclipse project properties, output folder is bin/classes for both.

My Android project is a maven project but not android test project.

Could you help me ?

Thanks

Jonathan Lebrun
  • 1,462
  • 3
  • 20
  • 42

1 Answers1

2

You should take a look at robolectric : http://robolectric.org/

This will allow you to test sqllite operation from a junit point of view. Robolectric "emulate" the android environnment from your favorite jvm on your dev machine.

Typically, a test then looks like this :

@RunWith(GuiceRobolectricJUnitRunner.class)
public class PhotoDatabaseTest {

    @Inject
    private Context context;

    @Inject
    private SharedPreferences sharedPreferences;

    @Test
    public void dataInsertBaseTest() throws SQLException {
        PhotosUploadDataSource photosUploadDataSource = new PhotosUploadDataSource(context);
        photosUploadDataSource.deleteAll();

        MediaItem mediaItem = new MediaItem();
        mediaItem.setLocation("/test/");
        mediaItem.setName("photo.jpg");
        mediaItem.setSize(5496849);
        mediaItem.setStatus(MediaItem.STATUS_PENDING);
        mediaItem.setType("images/jpg");
        MediaItem resultItem = photosUploadDataSource.createMediaItem(mediaItem);
        assertNotNull(resultItem);
        Utils.displayObject(resultItem);
    }
  } 

GuiceRobolectricJUnitRunner is your typical test runner junit thing (here with guice but you can do it without it). One of the interesting thing is that you can simulate all kind of interesting behaviors as your database does not persist between tests (or you can by implementing a pre population in a @beforeTest). More here : http://robolectric.org/customizing.html

Gomoku7
  • 1,362
  • 13
  • 31