- 起因
- 在Android studio 剛出。本人就想弄單元測試,可惜當時Android studio不知道抽什么風(准確來說,應該是我不會弄而已)。無法執行到相應的代碼。
后來今天突然自己又抽風。又想去弄一下Android junit。 - 本文基於做過Eclipse開發使用過Android junit,如果Eclipse的Android Junit沒有使用過,就我沒有說過吧!
- 准備環境,配置
- 官網Demo地址:https://github.com/googlesamples/android-testing-templates.git
- 環境
- 根據demo中
- 單純想運行java的單元測試就引入
// Dependencies for local unit tests
testCompile 'junit:junit:' + rootProject.ext.junitVersion
testCompile 'org.mockito:mockito-all:' + rootProject.ext.mockitoVersion
testCompile 'org.hamcrest:hamcrest-all:' + rootProject.ext.hamcrestVersion - 想運行Android的Junit得引入
// Android Testing Support Library's runner and rules
androidTestCompile 'com.android.support.test:runner:' + rootProject.ext.runnerVersion
androidTestCompile 'com.android.support.test:rules:' + rootProject.ext.rulesVersion - 最后在 defaultConfig 節點添加
defaultConfig {
testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
} - 以上配置要配置在“啟動項目中”build.gradle文件中,方可自動關聯上啟動項目
- Android Studio本來啟動項目中的測試代碼分為兩個目錄
- 如果是通過更改“sourceSets”的話。那就要得重新配置注明相應的文件夾(這是Eclipse轉AS導出的配置)
sourceSets{
sourceSets{
main{
java.srcDirs = ['src']
}
androidTest{
java.srcDirs = ['androidTest/src']
}
test{
java.srcDirs = ['test/src']
}
} - 最后就把相應的文件放入具體目錄
- androidTest “Android的Junit”
- test “java的單元測試”
- 代碼
- junit
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
System.out.println("123");
}
} - Android junit
public class AndroidRuntimeCodeTest extends AndroidTestCase {
public void testHello() throws Exception {
System.out.println("testHello");
}
} - 結論
- 注意事項
- 以前Eclipse做單元測試得往AndroidManifest.xml標明
<manifest ><instrumentationandroid:name="android.test.InstrumentationTestRunner"android:targetPackage="com.example.viewtest" />
</manifest>-
<application>
<uses-library android:name="android.test.runner" /></application> - Android studio就要在build.gradle
- 導入相應的包
- 在
android{defaultConfig {testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'}} - 還有一點:就是“測試使用的需要的包”遇到與“啟動項目的包”沖突時,使用
configurations.all {
resolutionStrategy {
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'
forcedModules = ['com.android.support:support-annotations:23.0.1']
}
}