java – Espresso 2.0 – 在扩展junit3 testcase的类中使用@Test注释的方法

前端之家收集整理的这篇文章主要介绍了java – Espresso 2.0 – 在扩展junit3 testcase的类中使用@Test注释的方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当使用Espresso 2.0附带的新ActivityInstrumentationTestCase2类时,我得到了一个奇怪的警告方法,使用@Test内部类扩展junit3 testcase.

我的课程看起来就像谷歌提供的那样:

  1. import android.support.test.InstrumentationRegistry;
  2. import android.support.test.runner.AndroidJUnit4;
  3. import android.test.ActivityInstrumentationTestCase2;
  4. import android.test.suitebuilder.annotation.LargeTest;
  5.  
  6. import org.junit.After;
  7. import org.junit.Before;
  8. import org.junit.Test;
  9. import org.junit.runner.RunWith;
  10.  
  11. import static android.support.test.espresso.matcher.ViewMatchers.assertThat;
  12. import static org.hamcrest.Matchers.notNullValue;
  13.  
  14. @RunWith(AndroidJUnit4.class)
  15. @LargeTest
  16. public class MyCoolActivityTests extends ActivityInstrumentationTestCase2<MyCoolActivity> {
  17.  
  18. private MyCoolActivity mActivity;
  19.  
  20. public MyCoolActivityTests() {
  21. super(MyCoolActivity.class);
  22. }
  23.  
  24. @Before
  25. public void setUp() throws Exception {
  26. super.setUp();
  27. injectInstrumentation(InstrumentationRegistry.getInstrumentation());
  28. mActivity = getActivity();
  29. }
  30.  
  31. @Test
  32. public void checkPreconditions() {
  33. assertThat(mActivity,notNullValue());
  34. // Check that Instrumentation was correctly injected in setUp()
  35. assertThat(getInstrumentation(),notNullValue());
  36. }
  37.  
  38. @After
  39. public void tearDown() throws Exception {
  40. super.tearDown();
  41. }
  42. }

我已经为build.gradle添加了所​​有必要的东西:

  1. android {
  2. defaultConfig {
  3. testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  4. }
  5. }
  6.  
  7. dependencies {
  8. androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
  9. androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
  10. }

有没有办法让这个警告消失?

解决方法

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测试用例类中可用的功能. (这不再是必要的.)

猜你在找的Java相关文章