Why espresso needs test method names to start with "test" even though it is using AndroidJunit4 runner?

时间:2015-06-25 18:46:06

标签: android unit-testing android-espresso

I have been trying to run espresso tests using AndroidJunit4 runner. Here is my Test Class. @RunWith(AndroidJUnit4.class) public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity> { public MyActivityTest() { super(MyActivity.class); } @Before public void setUp() throws Exception { super.setUp(); injectInstrumentation(InstrumentationRegistry.getInstrumentation()); getActivity(); } @Test public void shouldAssert() { onView(withId(someId)).check(matches(isDisplayed())); } } I have been trying to run this test via ./gradlew connectedCheck from command line but for some reason it does not recognize this test. I am able to run this test via Android Studio though. If I rename my test method from shouldAssert to testShouldAssert gradle is able to recognize this as a test and runs it successfully. I am puzzled since in Junit4 style test method names need not start with test. Anybody has any idea about this? [EDIT] Here is my build.gradle file android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } dependencies { androidTestCompile('com.android.support.test.espresso:espresso-core:2.2') { exclude group: 'com.android.support', module: 'support-annotations' } androidTestCompile('com.android.support.test.espresso:espresso-intents:2.2') { exclude group: 'com.android.support', module: 'support-annotations' } }

2 个答案:

答案 0 :(得分:0)

从命令行运行时,请确保gradle正在使用jUnit4 runner。

将testInstrumentationRunner添加到build.gradle文件

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

如果没有这个跑步者,将使用默认的jUnit3跑步者,这需要测试方法以&#34; test&#34;

开头

答案 1 :(得分:0)

不要扩展ActivityInstrumentationTestCase2,使用@Rule注释:

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

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

  @Test
  public void shouldAssert() {
    onView(withId(someId)).check(matches(isDisplayed()));
  }
}