Question

I'm trying to use robolectric to avoid starting the emulator for every test run. I set up everything following this (very good) tutorial: http://www.peterfriese.de/unit-testing-android-apps-with-robolectric-and-eclipse/ Unfortunately I get an error:

java.lang.RuntimeException: Window creation failed!
at org.robolectric.shadows.ShadowActivity.getWindow(ShadowActivity.java:329)
at org.robolectric.shadows.ShadowActivity.findViewById(ShadowActivity.java:275)
at android.app.Activity.findViewById(Activity.java)
at MainActivityTest.shouldNotBeNull(MainActivityTest.java:32)
    (...)

This is my code:

import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import static org.fest.assertions.api.ANDROID.assertThat;


import android.widget.Button;
import android.widget.EditText;


import com.abs.databaseprototype.MainActivity;
import com.abs.databaseprototype.R;

@RunWith(RobolectricTestRunner.class)
public class MainActivityTest {
private MainActivity activity;

@Before
public void setup() {
  activity = Robolectric.buildActivity(MainActivity.class).get();
}
@Test
public void shouldNotBeNull() {
  assertThat(activity).isNotNull();

  Button btnPatients = (Button) activity.findViewById(R.id.btnPatients);
  assertThat(btnPatients).isNotNull();
//
//    Button btnSpecialties = (Button) activity.findViewById(R.id.btnSpecialites);
//    assertThat(btnSpecialties).isNotNull();
//
//    Button btnTreat = (Button) activity.findViewById(R.id.btnTreat);
//    assertThat(btnTreat).isNotNull();
//    
//    EditText editText = (EditText) activity.findViewById(R.id.edit_query);
//    assertThat(editText).isNotNull();
      }

  @Test
  public void shouldFail() {
      assertTrue(false);
  }
}

Any ideas?

Was it helpful?

Solution

Ok, I found the solution. There's a mistake in the tutorial. You have to create the activity first, so write activity = Robolectric.buildActivity(LoginActivity.class).create().get(); instead of activity = Robolectric.buildActivity(LoginActivity.class).get(); And there you go. What I learned today: Always check the documentation. :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top