【问题标题】:How to use unit testing to test that a button launches the correct Activity如何使用单元测试来测试按钮是否启动了正确的 Activity
【发布时间】:2012-03-19 03:44:48
【问题描述】:

我正在尝试编写一个单元测试来测试按钮在单击时是否启动正确的活动,但我无法确定要使用的正确代码。 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);
                    }
                }
            );



}
}

【问题讨论】:

  • 你能发布更多异常堆栈跟踪吗?
  • 感谢 yorkw,但我决定使用 Robolectric 来实施测试。

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


【解决方案1】:

尝试检查仪器是否不存在。运行此命令将给出项目环境中当前检测的列表:

$ adb shell pm list instrumentation

希望对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多