Reputation:
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 sendEmptyMessage(...)
.
In my Activity I have a "addFoo(Foo foo)
" method that updates an array and then calls "sendEmptyMessage(1)
", and I have a handleMessage
method that calls the ListView's adapter to tell it the data has changed.
I've boiled the unit test down to, roughly:
public void testAddFoo() {
Foo foo = new Foo();
assertTrue(mActivity.addFoo(foo));
assertTrue(mActivity.getHandler().hasMessages(1));
assertFalse(mActivity.getHandler().hasMessages(1));
assertTrue(mActivity.fooListNotEmpty());
}
Naturally it is failing on that assertFalse()
(this is a contrived example, simplifying it as best as I can).
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.
FWIW, I'm pretty sure that the handleMessage code is correct because if I call it directly (inside @UiThreadTest
) like so:
@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());
}
the test ends up working as expected.
Upvotes: 1
Views: 7450
Reputation: 301
If your Activity implements Handler.Callback and you want messages to show up in your handleMessage method, then you need to pass in your Activity when you initialize the Handler in onCreate.
mHandler = new Handler(this);
I know you got the member Handler approach working, but I'm adding this for people like me who show up here trying to figure out how to get the Handler.Callback interface approach working.
Upvotes: 2
Reputation: 8533
If you are implementing Handler.Callback
in your activity then you should just do
assertTrue(mActivity.hasMessages(1));
otherwise do not implement the callback and use
mHandler = new Handler() {
// override Handler methods as required
// ie handleMessage(Message msg)
};
and
assertTrue(mActivity.mHandler.hasMessages(1));
Upvotes: 1