我在使用Robolectric测试活动中的回调时遇到了问题。
我有一项活动:
public class MainActivity extends Activity {
public static String value;
public Handler sHandler;
public Handler.Callback sHandlerCallback = new Handler.Callback(){
@Override
public boolean handleMessage(Message msg) {
value = "SEND_REQUEST_MSG";
changeName();
return true;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendMessage();
}
});
HandlerThread handlerThread = new HandlerThread("estat");
handlerThread.start();
sHandler = new Handler(handlerThread.getLooper(), sHandlerCallback);
}
public void sendMessage()
{
sHandler.obtainMessage().sendToTarget();
}
public void changeName()
{
runOnUiThread (new Thread(new Runnable() {
public void run() {
TextView t= (TextView)findViewById (R.id.textToDisplay);
t.setText(value);
}
}));
}}
使用Robolectric进行一次测试:
@RunWith(CustomRobolectricRunner.class)
public class TestApplicationTest {
private MainActivity activity;
@Test
public void testCreateMainActivity() throws InterruptedException {
activity = Robolectric.buildActivity(MainActivity.class).create().get();
Button pressMeButton = (Button) activity.findViewById(R.id.button);
pressMeButton.performClick();
Robolectric.runBackgroundTasks();
Robolectric.runUiThreadTasksIncludingDelayedTasks();
assertEquals("SEND_REQUEST_MSG", activity.value);
}}
事实上,当我从手机启动活动时,当我单击活动中指定的按钮时,我们调用方法sendMessage并向队列添加消息。此消息由回调中的handleMessage方法处理,该方法更改属性值并调用ChangeName()。
但是当我使用./gradlew clean build从命令行执行测试时。测试失败,出现断言错误,告诉我值为空!
那么我们可以用Robolectric测试callBack吗?
非常感谢你!