EightBitBoy
EightBitBoy

Reputation: 683

Testing an Android library with Robolectric

I created a library which can be used in an Android environment. At the moment it contains Plain Old Groovy Objects, there are no Android dependencies. Tests for those POGOs run without problems.

To extend the library's features I create classes which inherit from Android classes or rely on them, I want to test those too. Of course tests should be part of the library and should not be implemented as a part of an Android application project which includes the library.

I know that an application can be tested with the help of Robolectric and it works pretty well but I see no possibility of using it without a whole Android application behind it.

Is there a way to test a library with Android dependencies and Robolectric?

I am using Android Studio 1.2.

Upvotes: 9

Views: 2047

Answers (1)

annaskulimowska
annaskulimowska

Reputation: 61

I think that Robolectric is a good choice for you. For example if you wrote a class that inherits from the DialogFragment you can see if it behaves correctly:

@RunWith(RobolectricTestRunner.class)
public class ProgressDialogFragmentTest {
private static final String MESSAGE_KEY = "KEY_PROGRESS_MESSAGE";
private static final String TEST_MESSAGE = "test message";

@Test
public void argumentsContainExpectedKey() {
    //given
    ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(TEST_MESSAGE);

    //when
    boolean containsExpectedKey = fragment.getArguments().containsKey(MESSAGE_KEY);

    //then
    assertTrue(containsExpectedKey);
}

@Test
public void argumentsContainsValidMessage() {
    //given
    ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(TEST_MESSAGE);

    //when
    String actualMessage = fragment.getArguments().getString(MESSAGE_KEY);

    //then
    assertEquals(TEST_MESSAGE, actualMessage);
}

@Test
public void createdDialogIsProgressDialog() {
    //given
    ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(TEST_MESSAGE);
    FragmentTestUtil.startFragment(fragment);

    //when
    Dialog dialog = fragment.getDialog();

    //then
    assertTrue(dialog instanceof ProgressDialog);
}

@Test
public void dialogIsHiddenBeforeRunShowMethod() {
    //given
    ProgressDialogFragment fragment = ProgressDialogFragment.newInstance(TEST_MESSAGE);
    FragmentTestUtil.startFragment(fragment);

    //when
    ProgressDialog dialog = (ProgressDialog) fragment.onCreateDialog(fragment.getArguments());
    boolean showing = dialog.isShowing();

    //then
    assertFalse(showing);
}

}

Upvotes: 1

Related Questions