I have issues to test a callback in an activity using Robolectric.
I have one activity :
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);
}
}));
}}
and one test using 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);
}}
So the fact is when I launch the activity from my phone, when I click the button specified in the activity we call the method sendMessage and add a Message to the queue. This message is handle by the method handleMessage in the callback which change the attribute value and call ChangeName().
But when I execute the test from command line with ./gradlew clean build. The test fails with an assertion error that tells me the value is null !
So can we test callBack with Robolectric ?
Thanks you very much !
Aucun commentaire:
Enregistrer un commentaire