1

我正在测试一个 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();            
            }
        });       
    }

}
4

3 回答 3

1

试试Robotium,更少的代码和更好的方法,比如waitForDialog().

于 2013-08-22T12:36:23.710 回答
0
DialogCredits dialog  = new DialogCredits(this); 

if(!dialog.isShowing())
{  
    dialog.show(); 
}

将此代码放在开关盒中

于 2013-08-22T12:31:19.697 回答
0

那么我有同样的问题。

我所做的是:

private YourDialog mDialog;

onCreate :
initDialog();

public void initDialog() {    
mDialog = new YourDialog (this)
    enter code here
}
public boolean isDialogShowing() {
return mDialog.isVisible();
}

好吧,您必须保留对对话框的引用,以便检查是否可见,如果您一直创建新对话框,您将丢失最后一个对话框引用。

于 2013-08-22T12:40:59.020 回答