android – 如何测试已广播的意图

当点击“记录”按钮时,我正在广播一个意图.传递一个布尔变量,显示录制是否已开始.生成意图的代码是:
Intent recordIntent = new Intent(ACTION_RECORDING_STATUS_CHANGED);
recordIntent.putExtra(RECORDING_STARTED,getIsRecordingStarted());
sendbroadcast(recordIntent);

为了测试这段代码,我在测试中注册一个接收器.收到意图但传递的变量不一样.如果我调试代码,我可以看到该值与发送时相同,但是当我得到它时,它的值不一样.

@Test
public void pressingRecordButtonOnceGenerateStartRecordingIntent()
        throws Exception {
    // Assign
    AppActivity activity = new AppActivity();
    activity.onCreate(null);
    activity.onResume();

    activity.registerReceiver(new broadcastReceiver() {
        @Override
        public void onReceive(Context arg0,Intent intent) {
            // Assert
            ShadowIntent shadowIntent = Robolectric.shadowOf(intent);
            assertthat(shadowIntent
                    .hasExtra(AppActivity.RECORDING_STARTED),equalTo(true));
            Boolean expected = true;
            Boolean actual = shadowIntent.getExtras().getBoolean(
                    AppActivity.RECORDING_STARTED,false);
            assertthat(actual,equalTo(expected));

        }
    },new IntentFilter(
            AppActivity.ACTION_RECORDING_STATUS_CHANGED));

    ImageButton recordButton = (ImageButton) activity
            .findViewById(R.id.recordBtn);

    // Act
    recordButton.performClick();
    ShadowHandler.idleMainLooper();

}

我也测试了实际的意图,而不是它的阴影,但结果相同

解决方法

使用get()而不是getBoolean()为我工作.
public void pressingRecordButtonOnceGenerateStartRecordingIntent()
        throws Exception {
    // Assign
    BreathAnalyzerAppActivity activity = new AppActivity();
    activity.onCreate(null);
    activity.onResume();

    activity.registerReceiver(new broadcastReceiver() {
        @Override
        public void onReceive(Context arg0,Intent intent) {
            // Assert
            assertthat(intent
                    .hasExtra(AppActivity.RECORDING_STARTED),equalTo(true));
            Boolean expected = true;
            Boolean actual = (Boolean)intent.getExtras().get(
                    AppActivity.RECORDING_STARTED);
            assertthat(actual,equalTo(expected));


        }
    },new IntentFilter(
            AppActivity.ACTION_RECORDING_STATUS_CHANGED));

    ImageButton recordButton = (ImageButton) activity
            .findViewById(R.id.recordBtn);

    // Act
    recordButton.performClick();
    ShadowHandler.idleMainLooper();

}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...