2017-02-22 320 views
0

Android Studion 2.2.3Android。 @RunWith(AndroidJUnit4.class) - 無法在包中解析「androidTest」

安裝Android支持知識庫 - ver。 44.0.0

我的設置都在爲咖啡官方網站:

https://google.github.io/android-testing-support-library/docs/espresso/setup/index.html

我嘗試在包androidTest寫儀器測試咖啡(Espresso)。

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

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

    @Test 
    public void myTest() { 
     assert(true); 
    } 
} 

在我的build.gradle:

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

所以我在文件夾中的src/androidTest/JAVA/COM/myCompany中/

StringUtilAndroidTest代碼創建StringUtilAndroidTest我的依賴關係:

testCompile 'junit:junit:4.12' 
testCompile 'org.hamcrest:hamcrest-library:1.3' 
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' 
androidTestCompile 'com.android.support.test:testing-support-lib:0.1 

StringUtilAndroidTest我得到編譯錯誤:

@RunWith(AndroidJUnit4.class) 

無法解析符號RunWith

爲什麼?

+0

除了將androidTestCompile行添加到build.gradle之外,您還記得在Java文件的頂部導入類嗎?即'import org.junit.runner.RunWith;' – Bill

+0

import org.junit.runner.RunWith; - 無法解析符號'RunWith' – Alexei

回答

2

簡短回答:將此添加到您的依賴項中,您就是金。

androidTestCompile 'junit:junit:4.12' 
androidTestCompile 'org.hamcrest:hamcrest-library:1.3' 

龍答:

在默認配置下,一個Android Studio項目有兩個不同的測試 「變種」:test & androidTest。前者使用'src/test/java',後者使用'src/androidTest/java'(這是你的場景)。

兩者之間存在很大差異:androidTest需要模擬器或設備才能運行,而test則不需要。這意味着test運行速度要快得多(通常在IDE上幾秒鐘),但它無法訪問Android Framework(例如活動,上下文&等)。另一方面,androidTest需要更長的時間才能運行(更不用說模擬器本身的等待時間了),但它確實擁有Android框架(因爲它運行在一個框架中)。

由於它們是兩個獨立的變體,因此您還需要分別聲明它們的依賴關係。 testCompileandroidTestCompile各自僅將這種依賴性添加到它們自己的變體中。要在兩者上都有JUnit,你必須聲明依賴兩者 - 實質上是「重複」該行。

P.S .:請注意,當您使用compile時,它會將其添加到所有變體,因此您不必重複非測試依賴關係。

0

您可能錯過了一些依賴關係。

//App's dependencies, including test 
compile 'com.android.support:support-annotations:22.2.0' 

// Testing-only dependencies 
androidTestCompile 'com.android.support.test:runner:0.5' 
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2' 
androidTestCompile 'junit:junit:4.12' 

testCompile 'junit:junit:4.12' 

希望這會解決你的代碼。

+0

沒有幫助。我得到相同的錯誤 – Alexei

+0

我剛剛測試過。他們在我的情況下工作。 –