我正在测试一个 Android 应用程序。目前我正在为 MainActivity 编写测试。选择选项菜单的项目时,有一些对话框可以打开:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
new DialogCredits(this).show();
return true;
/.../
}
我想测试对话框是否从 JUnit 测试用例成功打开。我当前的测试代码如下所示:
public class MainActivityFunctionalTest extends
ActivityInstrumentationTestCase2<MainActivity> {
private MainActivity activity;
private @Mock MenuItem item;
public MainActivityFunctionalTest() {
super(MainActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
MockitoAnnotations.initMocks(this);
setActivityInitialTouchMode(false);
activity = getActivity();
}
@SmallTest
public void testOnOptionsItemSelected() {
when(item.getItemId()).thenReturn(android.R.id.home);
assertTrue(activity.onOptionsItemSelected(item));
// verify that the correct dialog was successfully opened
// --->code missing here<---
}
}
DialogCredits 类的代码:
public class DialogCredits extends Dialog{
public DialogCredits(Context context) {
super(context);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.dialog_credits_title);
setContentView(R.layout.dialog_credits);
final Dialog d = this;
Button buttonOk = (Button) findViewById(R.id.dialog_credits_button_ok);
buttonOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// close dialog
d.dismiss();
}
});
}
}