vendredi 4 mars 2016

Integration Test with a Broadcast Receiver without a concrete Activity.class

My App provides an Interface via IntentFilters for other apps to communicate with.

Internally I use BroadcastReceivers to translate those filtered Intents into POJOs and post them into my EventBus (Greenrobot v3).

My Problem:
I abuse my MainActivity.class for ActivityTestRule instantiation just for the purpose as "context donor" for my Tests:

mContext = mActivityRule.getContext();

Where as I really want to use some sort of "anonymous activity". I tried to use:

mContext = InstrumentationRegistry.getContext();

But as soon as I register my receiver, the test throws a java.lang.SecurityException. Is there a way to circumvent this exception?

Here is a skeleton of my TestCase:

@MediumTest
@RunWith(AndroidJUnit4.class)
public class StackoverflowQuestionTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule 
        = new ActivityTestRule<>(MainActivity.class);

    Person mPerson;
    CountDownLatch mLock;
    mContext = mActivityRule.getActivity();

    @Before
    public void setUp() {
        mLock = new CountDownLatch(1);
        mPerson = null;

        PersonReceiver receiver = new PersonReceiver();
        IntentFilter filter = receiver.getPredefinedFilter();
        mContext.registerReceiver(receiver, filter);
    }

    @Test
    public void PersonReceiver_seats_a_Person_on_the_EventBus() throws InterruptedException {
        EventBus.getDefault().register(this);

        mContext.sendBroadcast(new MockedPersonIntent("Waldo"));

        mLock.await();

        assertThat(Person.getName(), is(equalTo("Waldo")));
    }

    @Subscribe
    public void onPerson(Person person) {
        Person = person;
        mLock.countDown();
    }
}

Aucun commentaire:

Enregistrer un commentaire