Robolectric自定义ShadowSQLiteOpenHelper

时间:2012-11-27 15:25:10

标签: android unit-testing testing robolectric

前一段时间开始使用Robolectric,我目前正在运行一些创建自己的阴影对象的问题。我编写了一些代码来测试我自定义的SQLiteOpenHelper类的行为,它基本上只调用我的数据库表的onCreate方法。

@RunWith(SharedDatabaseHelperTestRunner.class)
public class SharedDatabaseHelperTest {

    private SharedDatabaseHelper helper;

    @Before
    public void setUp() 
            throws Exception {
        helper = new SharedDatabaseHelper(Robolectric.application);


    @Test
    public void shouldCallOnCreateOfDatabaseTables() 
            throws Exception {
        helper.onCreate(null);

        assertTrue(ShadowTweetTable.onCreateCalled);
    }

    @Test 
    public void shouldCallOnUpdateOfDatabaseTables() 
            throws Exception {
        helper.onUpgrade(null, 0, 0);

        assertTrue(ShadowTweetTable.onUpgradeCalled);
    }

数据库表的shadow对象只设置一些布尔变量,确保onCreate被调用:

@Implements(TweetTable.class)

public class ShadowTweetTable {

    public static boolean onCreateCalled = false;
    public static boolean onUpgradeCalled = false;

    @Implementation
    public static void onCreate(SQLiteDatabase database) {
        onCreateCalled = true;
    }

    @Implementation
    public static void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
        onUpgradeCalled = true;
    }

当我运行测试时,RobolectricTestRunner告诉我TweetTable没有阴影字段,尽管我的自定义testrunner绑定了我的阴影类:

公共类SharedDatabaseHelperTestRunner扩展了RobolectricTestRunner {

public SharedDatabaseHelperTestRunner(Class<?> testClass)
        throws InitializationError {
    super(testClass);
}

@Override
protected void bindShadowClasses() {
    Robolectric.bindShadowClass(ShadowTweetTable.class);
}

}

0 个答案:

没有答案