对ActivityInstrumentationTestCase2使用JUnit注释测试

时间:2015-08-13 16:23:39

标签: android junit

我使用ActivityInstrumentationTestCase2来测试我的Android应用。目前,我通过命名方法testXXX来创建测试方法,其中XXX是一些任意名称。是否可以省略“测试”命名约定并按照JUnit的方式注释方法?我发现这个更好,因为我可以创建具有testXXX名称但不会被调用的方法。

1 个答案:

答案 0 :(得分:1)

您可以使用@RunWith(AndroidJUnit4.class)

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityTest extends ActivityInstrumentationTestCase2<MyCoolActivity> {

private MainActivity mActivity;

public MainActivityTest() {
    super(MainActivityTest.class);
}

@Before
public void setUp() throws Exception {
    super.setUp();
    injectInstrumentation(InstrumentationRegistry.getInstrumentation());
    mActivity = getActivity();
}

@Test
public void checkPreconditions() {
    assertThat(mActivity, notNullValue());
    // Check that Instrumentation was correctly injected in setUp()
    assertThat(getInstrumentation(), notNullValue());
}

@After
public void tearDown() throws Exception {
    super.tearDown();
}
}

在build.gradle中添加依赖项

android {
   defaultConfig {
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}

dependencies {
// Testing-only dependencies
// Force usage of support annotations in the test app, since it is internally used by the runner module.
androidTestCompile 'com.android.support:support-annotations:23.0.1'
androidTestCompile 'com.android.support.test:runner:0.4'
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
}

@Before - 此方法在每次测试之前执行。它用于准备测试环境(例如,读取输入数据,初始化类)。

@Test:@Test注释将方法标识为测试方法。

@After: 每次测试后执行此方法。它用于清理测试环境(例如,删除临时数据,恢复默认值)。它还可以通过清理昂贵的内存结构来节省内存。

相关问题