Android 无具体活动的广播接收器集成测试。类

Android 无具体活动的广播接收器集成测试。类,android,testing,android-intent,broadcastreceiver,integration-testing,Android,Testing,Android Intent,Broadcastreceiver,Integration Testing,我的应用程序通过IntentFilter为其他应用程序提供了一个与之通信的接口 在内部,我使用BroadcastReceivers将过滤后的意图转换为POJO,并将其发布到我的EventBus(Greenrobot v3)中 我的问题: 我将ActivityTestRule与存根MainActivity.class-文件结合使用,以获得上下文,我可以在其上注册我的广播接收器并发送意图s: mContext = mActivityRule.getContext(); 因为我真的想使用某种“匿名活

我的应用程序通过IntentFilter为其他应用程序提供了一个与之通信的接口

在内部,我使用BroadcastReceivers将过滤后的意图转换为POJO,并将其发布到我的EventBus(Greenrobot v3)中

我的问题:
我将
ActivityTestRule
与存根MainActivity.class-文件结合使用,以获得
上下文
,我可以在其上注册我的
广播接收器
并发送
意图
s:

mContext = mActivityRule.getContext();
因为我真的想使用某种“匿名活动”。这样我就可以删除存根MainActivity.class文件。我尝试使用:

mContext = InstrumentationRegistry.getContext();
但一旦我注册了接收器,测试就会抛出一个
java.lang.SecurityException
。有没有办法绕过这个例外

以下是我的测试用例的框架:

@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();
    }
}
@MediumTest
@RunWith(AndroidJUnit4.class)
公共类StackoverflowQuestionTest{
@统治
公共活动测试规则mActivityRule
=新的ActivityTestRule(MainActivity.class);
人与人;
倒计时锁存锁存;
mContext=mActivityRule.getActivity();
@以前
公共作废设置(){
mLock=新的倒计时锁存器(1);
mPerson=null;
PersonReceiver=新的PersonReceiver();
IntentFilter=receiver.getPredefinedFilter();
mContext.registerReceiver(接收器、过滤器);
}
@试验
public void PersonReceiver在事件总线()抛出InterruptedException上为一个人设置座位{
EventBus.getDefault()寄存器(此);
sendBroadcast(新的模拟人物内容(“Waldo”);
mLock.wait();
断言(Person.getName(),是(equalTo(“Waldo”));
}
@订阅
公众人士(人){
人=人;
mLock.countDown();
}
}

解决方案比我想象的要简单

mContext = InstrumentationRegistry.getTargetContext();
发生安全异常是因为我使用了
getContext()
,它返回了与包相关的上下文,其中as
getargetcontext()
返回了与整个应用程序相关的上下文,我的接收方也注册了该应用程序

完全如合同中所述