android - 如何使用单元测试来测试按钮是否启动了正确的 Activity

标签 android unit-testing android-activity android-button

我正在尝试编写一个单元测试来测试单击按钮时是否启动了正确的 Activity ,但我无法确定要使用的正确代码。 testButton 方法确实运行并通过了测试,但随后会导致错误:

[2012-02-29 16:18:08 - TroubleShootingAppTest] Test run failed: Instrumentation run failed due to 'java.lang.RuntimeException'

然后测试提前终止。谁能告诉我正确的代码应该是什么?

这是我的:

package com.integral.troubleshooter.test;

import com.integral.troubleshooter.Question;
import com.integral.troubleshooter.R;
import com.integral.troubleshooter.TroubleShooterActivity;

import android.app.Activity;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class TroubleShooterActivityTest extends
    ActivityInstrumentationTestCase2<TroubleShooterActivity> {

private TroubleShooterActivity mActivity;
private Button mButton;
private TextView mTextView;
private ImageView mImageView;
private String resourceString;
private Activity nextActivity;

public TroubleShooterActivityTest() {      
    super("com.integral.troubleshooter.TroubleShooterActivity",        TroubleShooterActivity.class);    
}

 /*
 * Sets up the test environment before each test.
 * @see android.test.ActivityInstrumentationTestCase2#setUp()
 */
@Override
protected void setUp() throws Exception {

    super.setUp();

    setActivityInitialTouchMode(false);


    mActivity = getActivity();

    mButton = (Button)mActivity.findViewById(R.id.troubleShooter);

    mTextView =  (TextView)mActivity.findViewById(R.id.title);

    mImageView = (ImageView)mActivity.findViewById(R.id.IntegralLogo);

    resourceString = mActivity.getString(R.string.CustomerSupport); 
}

public void testPreconditions() {
    assertTrue(mTextView != null);
    assertTrue(mImageView != null);
}

public void testText(){
    assertEquals(resourceString,(String)mTextView.getText());
}

public void testButton(){
     mActivity.runOnUiThread(
                new Runnable() {
                    public void run() {
                       mButton.performClick();
                       nextActivity =  getActivity();
                       assertEquals(nextActivity, Question.class);
                    }
                }
            );



}
}

最佳答案

尝试检查仪器是否不存在。运行此命令将提供项目环境中现有仪器的列表:

$ adb shell pm list instrumentation

希望对您有所帮助。

关于android - 如何使用单元测试来测试按钮是否启动了正确的 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9502800/

相关文章:

Android错误膨胀类SwipeRefreshLayout

android - 带有ListTiles和Button行的Flutter下拉菜单

unit-testing - 测试驱动开发成本节约

android - 在 android 中使用按钮开始相同的 Activity

android - 从不同的线程访问非托管对象抛出 IllegalStateException

java - 获取特定 JTable 单元格中的前景(字体)

c# - 我的 TDD 算法练习

android - 确定应用程序是否在后台运行

android - PendingIntent 在 Activity 重新加载时继续触发

java - "Cannot access database on the main thread"AsyncTask异常