gpt4 book ai didi

android - 单元测试广播接收器?

转载 作者:IT王子 更新时间:2023-10-28 23:59:12 27 4
gpt4 key购买 nike

这是我项目中的一个 BroadcastReceiver,我正在对其进行单元测试。当用户调用电话时,它会获取电话号码,并设置启动新 Activity 的 Intent ,并传入电话号码。

public class OutgoingCallReceiver extends BroadcastReceiver 
{
@Override
public void onReceive(Context xiContext, Intent xiIntent)
{
if (xiIntent.getAction().equalsIgnoreCase(Intent.ACTION_NEW_OUTGOING_CALL))
{
String phoneNum = xiIntent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

Intent intent = new Intent(xiContext, MyActivity.class);
intent.putExtra("phoneNum", phoneNum);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

xiContext.startActivity(intent);
setResultData(null);
}
}
}

到目前为止,我的单元测试如下所示:

public class OutgoingCallReceiverTest extends AndroidTestCase
{
private OutgoingCallReceiver mReceiver;

@Override
protected void setUp() throws Exception
{
super.setUp();

mReceiver = new OutgoingCallReceiver();
}

public void testStartActivity()
{
Intent intent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL);
intent.putExtra(Intent.EXTRA_PHONE_NUMBER, "01234567890");

mReceiver.onReceive(getContext(), intent);
}
}

这将贯穿代码,但我希望我的测试能够检查 Intent 是否已发送,并检查其上的电话号码。我该怎么做?

我还可以测试电话是否被取消(因为 setResultData(null) 行)?

最佳答案

corlettk 将我指向 Android 中的 MockContext 对象,这可以解决问题。我已经创建了它的一个子类,TestContext,它看起来像这样:

public class TestContext extends MockContext
{
private List<Intent> mReceivedIntents = new ArrayList<Intent>();

@Override
public String getPackageName()
{
return "com.mypackage.test";
}

@Override
public void startActivity(Intent xiIntent)
{
mReceivedIntents.add(xiIntent);
}

public List<Intent> getReceivedIntents()
{
return mReceivedIntents;
}
}

我的测试用例现在看起来像这样:

public class OutgoingCallReceiverTest extends AndroidTestCase
{
private OutgoingCallReceiver mReceiver;
private TestContext mContext;

@Override
protected void setUp() throws Exception
{
super.setUp();

mReceiver = new OutgoingCallReceiver();
mContext = new TestContext();
}

public void testStartActivity()
{
Intent intent = new Intent(Intent.ACTION_NEW_OUTGOING_CALL);
intent.putExtra(Intent.EXTRA_PHONE_NUMBER, "01234567890");

mReceiver.onReceive(mContext, intent);
assertEquals(1, mContext.getReceivedIntents().size());
assertNull(mReceiver.getResultData());

Intent receivedIntent = mContext.getReceivedIntents().get(0);
assertNull(receivedIntent.getAction());
assertEquals("01234567890", receivedIntent.getStringExtra("phoneNum"));
assertTrue((receivedIntent.getFlags() & Intent.FLAG_ACTIVITY_NEW_TASK) != 0);
}
}

关于android - 单元测试广播接收器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769315/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com