Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing ActiveAndroid with Robolectric

What can I do to get some test coverage on ActiveAndroid's ContentProvider in Robolectric? This simple test fails.

The model:

@Table(name = "Things")
    public class Thing extends Model {
    public Thing() {
        super();
    }
}

The test:

@RunWith(RobolectricTestRunner.class)
public class ContentProviderTest {

  @Test
  public void itShouldQuery() throws Exception {
    new Thing().save();
    ContentResolver cr = new MainActivity().getContentResolver();
    assertNotNull(
        cr.query(Uri.parse("content://org.example/things"), 
                   null, null, null, null));
  }
}

The resulting stack trace:

java.lang.NullPointerException: null
    at com.activeandroid.Cache.getTableInfo(Unknown Source)
    at com.activeandroid.Model.<init>(Unknown Source)
    at org.example.Thing.<init>(Thing.java:9)
    at org.example.ProviderTest.itShouldQuery(ProviderTest.java:25)

The application context should be ok. By default, Robolectric creates the application that appears in the manifest, which in this case is com.activeandroid.Application.

So, I'm puzzled why the tableInfo in Cache is not initialized. Normal application execution works fine.

like image 723
Fred Medlin Avatar asked May 01 '13 19:05

Fred Medlin


People also ask

Is Robolectric deprecated?

Robolectric is intended to be fully compatible with Android's official testing libraries since version 4.0. As such we encourage you to try these new APIs and provide feedback. At some point the Robolectric equivalents will be deprecated and removed.

What is Robolectric used for?

Robolectric handles inflation of views, resource loading, and lots of other stuff that's implemented in native C code on Android devices. This allows tests to do most things you could do on a real device.


1 Answers

To automatically scan ActiveAndroid Models automatically during maven unit tests requires a simple change to ModelInfo.scanForModel.

In that method, there is a "Robolectric fallback" which detects and scans paths containing "bin". This handles Model classes in Eclipse projects.

Maven compiles to target/classes. An additional check for "classes" in scan paths in ModelInfo does the trick.

Adding an ActiveAndroid pull request for this soon.

like image 74
Fred Medlin Avatar answered Oct 01 '22 14:10

Fred Medlin