在Dagger中你必须注入UI线程。运行JUnit时,您没有在UI线程上运行。为了使它工作,我们必须在UI线程上发布一个Runnable并等待它完成注入。
我的代码如下所示:
public void inject(final Object object) {
// We always has to inject on the main thread.
final CountDownLatch latch = new CountDownLatch(1);
Handler mainHandler = new Handler(FodoApplication.getAppContext().getMainLooper());
Runnable myRunnable = new Runnable() {
public void run() {
objectGraph.inject(object);
latch.countDown();
}
};
mainHandler.post(myRunnable);
try {
latch.await();
} catch (InterruptedException e) {
Log.e(TAG, "", e);
}
}
问题是当调用latch.await()时myRunnable不会启动。在运行JUnit时让Dagger注入的最佳方法是什么?