我是 Android 的新手,正在学习
BroadcastReceiver
。我正在尝试从 Android 单元测试 sendBroadcast
接收器,并尝试检查接收器收到的意图操作是否有效。如果我想从接收器发送意图数据到单元测试,有什么方法。
public class ExampleUnitTest {
private Context mContext;
private AsyncTableProcess sgTable;
private final static String WHOLE_HOME_ASYNC = "com.atv.intent.action.WHOLE_HOME_AE";
// Executes each task synchronously using Architecture Components.
@Rule
public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();
@Before
public void setUp() throws Exception {
mContext = mock(Context.class);
sgTable = new AsyncTableProcess();
}
@Test
public void addition_isCorrect() {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(WHOLE_HOME_ASYNC);
mContext.registerReceiver(sgTable, filter);
Intent intent = new Intent();
intent.setAction(WHOLE_HOME_ASYNC);
intent.putExtras(setWholeHomeBundleExtras());
mContext.sendBroadcast(intent);
}
}
public class AsyncTableProcess extends BroadcastReceiver {
private static final String sgsLiteWholeHomeAE = "com.atv.intent.action.WHOLE_HOME_AE";
@Override
public void onReceive(final Context context, Intent intent) {
final String message = intent.getAction();
//Response back to unitTest.
switch (message) {
case sgsLiteWholeHomeAE:
Bundle extras = intent.getExtras();
//updating hash table..
break;
}
}
}
我们不能在没有设备的情况下对android组件进行单元测试。但是使用 Robolectric 可以让它工作。这是我如何为 BroadcastReceiver 实现单元测试。
@RunWith(RobolectricTestRunner.class)
@Config(sdk = 29)
@DoNotInstrument
public class BroadCastReceiverTest extends TestCase {
private Context context;
private YourReceiver yourReceiver;
private int expectedResponseCode = 500;
@Before
public void setup(){
yourReceiver = new YourReceiver();
context = RuntimeEnvironment.application.getApplicationContext();
intent = new Intent(Constants.ACTION_YOUR_ACTION);
}
@Test
public void testResponse(){
intent.putExtra(Constants.ERROR_CODE,500);
yourReceiver.onReceive(context,intent);
assertEquals(expectedResponseCode,yourReceiver.getResponseCode());
}
}