android junit测试谷歌示例代码

时间:2012-11-20 23:04:41

标签: android junit

我已从developer.android

下载此代码
public class SpinnerTestActivity extends
        ActivityInstrumentationTestCase2<SpinnerActivity> {

    private SpinnerActivity mActivity;
    private Spinner mSpinner;
    private SpinnerAdapter mPlanetData;
    public static final int ADAPTER_COUNT = 9;
    public static final int INITIAL_POSITION = 0;
    public static final int TEST_POSITION = 5;

    private String mSelection;
    private int mPos;

    public SpinnerTestActivity() {
        super("com.android.example.spinner", SpinnerActivity.class);
    } // end of SpinnerActivityTest constructor definition

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

        setActivityInitialTouchMode(false);

        mActivity = getActivity();

        mSpinner = (Spinner) mActivity
                .findViewById(com.android.example.spinner.R.id.Spinner01);

        mPlanetData = mSpinner.getAdapter();

    } // end of setUp() method definition

    public void testPreConditions() {
        assertTrue(mSpinner.getOnItemSelectedListener() != null);
        assertTrue(mPlanetData != null);
        assertEquals(mPlanetData.getCount(), ADAPTER_COUNT);
    } // end of testPreConditions() method definition

    public void testSpinnerUI() {

        mActivity.runOnUiThread(new Runnable() {
            public void run() {
                mSpinner.requestFocus();
                mSpinner.setSelection(INITIAL_POSITION);
            } // end of run() method definition
        } // end of anonymous Runnable object instantiation
                ); // end of invocation of runOnUiThread
        this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
        for (int i = 1; i <= TEST_POSITION; i++) {
            this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
        } // end of for loop

        this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
        mPos = mSpinner.getSelectedItemPosition();
        mSelection = (String) mSpinner.getItemAtPosition(mPos);
        TextView resultView = (TextView) mActivity
                .findViewById(com.android.example.spinner.R.id.SpinnerResult);

        String resultText = (String) resultView.getText();

        assertEquals(resultText, mSelection);

    }
}

我的问题是:如何调用testSpinnerUI?来自哪里?我已阅读junit文档但无法弄清楚..谢谢!

1 个答案:

答案 0 :(得分:0)

但是,这是个愚蠢的问题。我在blog找到了答案。

测试用例的生命周期基本上是这样的:constructionsetUp()tests runtearDown()destructionsetUp()方法用于执行所有特定测试使用的任何常规初始化。在测试用例中运行的每个测试都是作为自己的方法实现的,其中方法名称以“test”开头。然后使用tearDown()方法取消初始化setUp()方法获取的任何资源。     每个特定的测试都有自己的方法,以“test”开头 - “test”方法名称前缀区分大小写!

我最初的问题是测试方法是如何运行的,因为没有人调用它。但是从上面的测试中,每种方法都应该进行测试,以便进行识别。