【问题标题】:ActivityInstrumentationTestCase2 vs ActivityTestRuleActivityInstrumentationTestCase2 与 ActivityTestRule
【发布时间】:2016-09-05 13:14:19
【问题描述】:

我需要在我的 Android 应用中测试一个活动。 ActivityInstrumentationTestCase2 的文档说:

此类提供单个活动的功能测试。

ActivityTestRule 的文档说:

此规则提供单个活动的功能测试。

几乎相同的词。除了我编写的两个示例之外,请执行相同的操作。那么我应该更喜欢ActivityTestRule 而不是ActivityInstrumentationTestCase2,反之亦然?

我看到的是扩展ActivityInstrumentationTestCase2 看起来像一个JUnit3 风格的测试(它的祖先是junit.framework.TestCase,测试方法应该以单词test 开头)。

使用 ActivityTestRule

package sample.com.sample_project_2;

import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.matcher.ViewMatchers.withId;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class ApplicationTest {

    @Rule
    public ActivityTestRule<SecAct> mActivityRule = new ActivityTestRule(SecAct.class);

    @Test
    public void foo() {
        onView(withId(R.id.editTextUserInput)).perform(typeText("SAMPLE"));

    }
}

扩展 ActivityInstrumentationTestCase2

package sample.com.sample_project_2;

import android.test.ActivityInstrumentationTestCase2;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.matcher.ViewMatchers.withId;


public class ApplicationTest2 extends ActivityInstrumentationTestCase2<SecAct> {

    public ApplicationTest2() {
        super(SecAct.class);
    }

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


    public void testFoo2() {
        onView(withId(R.id.editTextUserInput)).perform(typeText("SAMPLE 2"));

    }
}

【问题讨论】:

    标签: android unit-testing junit4 junit3


    【解决方案1】:

    对于您的示例,没有区别。你可以使用它们中的任何一个。

    根据 OO 原则,我们将“优先组合而不是继承”。 ActivityTestRule&lt;&gt; 的使用是通过组合实现的,而 ActivityInstrumentationTestCase2&lt;&gt; 是通过继承实现的。

    有时,我更喜欢为我的测试类创建一个通用基类,以重用通用初始化。这有助于我根据主题对测试进行分组。 ActivityTestRule&lt;&gt; 允许我做这样的事情。

    出于这些原因,我更喜欢ActivityTestRule&lt;&gt;。否则,我没有看到任何区别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 2017-02-15
      相关资源
      最近更新 更多