title: Unit testing Handler
body: <p>I am ultimately trying to unit test a custom base adapter, but I am stuck at one point: I am unable to figure out how to get the UI thread to process the message I have just passed to it via <code>sendEmptyMessage(...)</code>.</p>
  
  <p>In my Activity I have a "<code>addFoo(Foo foo)</code>" method that updates an array and then calls "<code>sendEmptyMessage(1)</code>", and I have a <code>handleMessage</code> method that calls the ListView's adapter to tell it the data has changed.</p>
  
  <p>I've boiled the unit test down to, roughly:</p>
  
  <pre><code>public void testAddFoo() {
    Foo foo = new Foo();
    assertTrue(mActivity.addFoo(foo));
    assertTrue(mActivity.getHandler().hasMessages(1));
    assertFalse(mActivity.getHandler().hasMessages(1));
    assertTrue(mActivity.fooListNotEmpty());
  }
  </code></pre>
  
  <p>Naturally it is failing on that <code>assertFalse()</code> (this is a contrived example, simplifying it as best as I can).</p>
  
  <p>What call can I make in to mActivity or its handler or looper to get it to process all pending messages? I have tried some suggestions I've read about calling Looper.loop(), within the UI thread, but those are stabs in the dark and they failed.</p>
  
  <p>FWIW, I'm pretty sure that the handleMessage code is correct because if I call it directly (inside <code>@UiThreadTest</code>) like so:</p>
  
  <pre><code>@UiThreadTest
  public void testAddFoo() {
    Foo foo = new Foo();
    assertTrue(mActivity.addFoo(foo));
    Message msg = Message.obtain();
    msg.what = 1;
    mActivity.handleMessage(msg);
    assertTrue(mActivity.fooListNotEmpty());
  }
  </code></pre>
  
  <p>the test ends up working as expected.</p>