Skip to content

Instantly share code, notes, and snippets.

@dschinkel
Last active August 16, 2019 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dschinkel/b9745d79e33cd6a741cf106d12d60cd2 to your computer and use it in GitHub Desktop.
Save dschinkel/b9745d79e33cd6a741cf106d12d60cd2 to your computer and use it in GitHub Desktop.
Roboelectric - Example of Finding a Child Fragment from a test
/*
Dave Schinkel's Notes after he wrote this test:
This is a test I wrote headlessly with Roboelectric around an existing Legacy codebase that's a mess.
We want to get some sort of confidence with an integration test which is what this test gave us for a
certain part of this codebase.
This test indirectly tests behavior further down by
checking what I ultimately expected to be rendered
We make the use of tags in android as a test markers, an easy way to find something in
the android tree without coupling your tests to implementation.
In this scenario, we have a Parent Fragment (CallFragment) which ultimately contains
a child fragment (DialingFragment). So first you need to get a hold of the parent, then
you can use android's getChildFragmentManager to walk the child fragment list contained in the parent.
Note:
Ideally we would not use mockito because it adds unecessary complexity to tests
as well as pigeonholes you into IMO bad practices, bad ways to TDD IMO.
Normally I'd prefer to find a way to just create a custom mock, stub, or dummy
but in this case the Call class is a final Java class in the Android API so we
couldn't do much with it in terms of custom mocking, so we really did not have a choice
but to use some mockito here
*/
import android.content.Intent;
import android.telecom.Call;
import CallManager;
import CallActivity;
import CallFragment;
import DialingFragment;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static junit.framework.TestCase.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.robolectric.Robolectric.buildActivity;
@RunWith(RobolectricTestRunner.class)
public class MakeCallTest {
@Test
public void MakeCallShowsDialing() {
Intent makeACall = new Intent(Intent.ACTION_CALL);
Call callMade = mock(Call.class);
when(callMade.getState()).thenReturn(Call.STATE_DIALING);
CallManager.getInstance().addCall(callMade);
CallActivity activity = buildActivity(CallActivity.class, makeACall).create().resume().get();
CallFragment callDisplay = (CallFragment) activity.getSupportFragmentManager().findFragmentByTag("CALL");
DialingFragment dialingDisplay = (DialingFragment) callDisplay.getChildFragmentManager().findFragmentByTag("DIALING");
assertTrue(dialingDisplay instanceof DialingFragment);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment