当使用Espresso 2.0附带的新ActivityInstrumentationTestCase2类时,我得到了一个奇怪的警告方法,使用@Test内部类扩展junit3 testcase.
我的课程看起来就像谷歌提供的那样:
import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import android.test.ActivityInstrumentationTestCase2; import android.test.suitebuilder.annotation.LargeTest; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.matcher.ViewMatchers.assertThat; import static org.hamcrest.Matchers.notNullValue; @RunWith(AndroidJUnit4.class) @LargeTest public class MyCoolActivityTests extends ActivityInstrumentationTestCase2<MyCoolActivity> { private MyCoolActivity mActivity; public MyCoolActivityTests() { super(MyCoolActivity.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 { androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0' androidTestCompile 'com.android.support.test:testing-support-lib:0.1' }
有没有办法让这个警告消失?
解决方法
ActivityInstrumentationTestCase2是一个JUnit 3测试用例,因为它从TestCase扩展.
@Test annotation is a replacement for the test-prefix naming convention used in JUnit 3. JUnit 4 test classes no longer require to extend TestCase or any of its subclasses. In fact JUnit 4 tests cannot extend TestCase,otherwise AndroidJUnitRunner will treat them as JUnit 3 tests.
http://developer.android.com/tools/testing-support-library/index.html#AndroidJUnitRunner
您可以迁移到由com.android.support.test提供的ActivityTestRule:规则:0.4(或更高版本),或坚持使用JUnit 3.
另一个选项是InstrumentationRegistry,由Espresso 2提供,它有getInstrumentation(),getContext(),getTargetContext()(以及更多).这些方法以静态方式提供对当前检测,测试上下文和目标上下文的访问.这使得编写自己的静态实用程序方法成为可能,以便在JUnit 4测试用例类中使用.这些实用程序将模仿当前仅在基本JUnit 3测试用例类中可用的功能. (这不再是必要的.)