2
在匕首中,你必須注入UI線程。運行JUnit時,您不在UI線程上運行。爲了使其工作,我們必須在UI線程上發佈一個Runnable,並等待它完成注入。如何注入ui-thread並等待注射完成後再繼續?
我的代碼如下所示:
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);
}
}
的問題是,myRunnable不啓動時調用磨片latch.await()。運行JUnit時使Dagger注入的最佳方式是什麼?