如何在UnitTest线程中运行volley onResponse

时间:2016-04-13 13:45:02

标签: java android multithreading android-volley realm

我正在为我的申请进行单元测试 我的单元测试类有这个方法

@Before
public void initialize() {
    mContext = InstrumentationRegistry.getTargetContext();
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(mContext).name("realmTest").inMemory().build();
    Realm.setDefaultConfiguration(realmConfiguration);
    mWorkoutsModel = new WorkoutsModel(mContext);
    mRealm = Realm.getInstance(realmConfiguration);
    mWorkoutsModel.registerListener(this);
}

@Test
public void getWorkouts() throws Exception {
    mWorkoutsModel.onStart();

    mLock.await();
    mWorkoutsModel.onStop();

}

@After
public void deInitialize() {
    mWorkoutsModel.unRegisterListener();
    mRealm.close();
}

和我的模特

@Override
public void onStart() {

    mRealm = Realm.getDefaultInstance();
        getDataFromApi();
}

private boolean getDataFromApi() {
    Constants.AllAPIs.ALLWorkouts allWorkouts = new Constants.AllAPIs.ALLWorkouts();
    if (Permissions.isInternetConnectionExist(mContext)) {
        mApiHandler.downLoadDataFromApi(AllWorkouts.class, allWorkouts.getBaseUrl(),
                new APIHandler.StringResponseHandler<AllWorkouts>() {
                    @Override
                    public void onResponse(AllWorkouts response) {
                            insertWorkouts(response.getWorkouts());
                },
                new APIHandler.ErrorResponseHandler() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }, TAG);

        return true;
    } else {
        return false;
    }
}
private void insertWorkouts(final List<Workout> workouts) {
    mCurrentInsertTransaction = mRealm.executeTransactionAsync(new Realm.Transaction() {
        @Override
        public void execute(Realm bgRealm) {
            bgRealm.copyToRealmOrUpdate(workouts);
        }
    }, new Realm.Transaction.OnSuccess() {
        @Override
        public void onSuccess() {
        }
    });
}

我的问题是unittest调用onStart,它在测试线程中的模型中创建了realm对象但是volley强制onResponse在UIThread上运行,这使得域抛出异常Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.

代码在正常情况下运行完美,但在测试中它失败

有人遇到同样的问题或能解决吗?

1 个答案:

答案 0 :(得分:1)

我通过在处理程序

中运行测试来解决我的问题
new Handler(mContext.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            try {
                mWorkoutsModel.onStart();
                mLock.await();
                mWorkoutsModel.onStop();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

希望能帮助某人