Android_AndroidX简介&Junit4
阅读原文时间:2023年07月08日阅读:1

AndroidX简介:

Android 9.0(API level 28)发布时,AndroidX也作为一个新的支持库发布出来了。AndroidX时Jetpack的一部分,它包含了现有的支持库和最新的Jetpack组件。

AndroidX 与 Android 操作系统分开提供,并与各个 Android 版本向后兼容。AndroidX 完全取代了支持库(android.support.v7或android.support.v4),不仅提供同等的功能,而且提供了新的库。所以对于使用AndroidX后,不需要因为使用v4还是v7库而烦恼了。

修改项目中的gradle.properties文件中将下面两个属性置为true就能完全使用AndroidX的库了。
android.useAndroidX:使用相应的 AndroidX 库,而非支持库
android.enableJetifier:重写其二进制文件,自动迁移现有的第三方库以使用 AndroidX

更多具体信息及如何使用请到android官网查看文档:

https://developer.android.google.cn/jetpack/androidx

Junit4:

这里简单记录分享下

背景:Android Studio中调试Room相关时碰到的问题(如 java.lang.ClassNotFoundException: Didn't find class "android.support.test.runner.AndroidJUnitRunner" )

Room调试中使用的是AndroidX的库,而默认Junit使用的是非AndroidX库,导致出现各种报错。理清这个,修改下依赖库即可解决问题。

1.在默认情况下,Android Studio使用的是非AndroidX支持库中的Junit的相关库,build.gradle(Module:app) 中关于Junit大概配置如下:

android {
compileSdkVersion 28
defaultConfig {
applicationId "com.flx.testjunit"
minSdkVersion 27
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

2.AndroidX库关于Junit的配置如下。

如AndroidX简介中所述,gradle.properties(Project Properties)中添加:

android.useAndroidX=true
android.enableJetifier=true

build.gradle(Module:app) 中:

android {
compileSdkVersion 28
defaultConfig {
applicationId "com.flx.testjunitandroidx"
minSdkVersion 27
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
implementation 'com.google.android.material:material:1.0.0-beta01'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
}

修改配置后 重新Build下工程,具体类中报错重新import对应的库类即可。

运行Junit:

下面是简单的示例图片

从上面看:

(1)点击1处的Structure即可出现2的窗口,右击2处即可执行

(2)4和5处已经左边有明显的结果提示,如上”passed:1 of 2“。5处有具体报错信息。

(3)3处有androidTes和test两个文件夹,有什么区别呢,

androidTest/java: Android单元测试,执行测试的时候需要连接Android设备(或AVD),需要Android环境。
test/java: JUnit单元测试,不需要Android依赖,运行在当前电脑中。

下图是便捷的创建测试:

常用断言:

assertEquals, 预期和实际相等,不相等则抛出异常和信息
assertNotEquals, 预期和实际不相等,相等则抛出异常和信息
assertNull,传入的为空,不为空抛出异常和信息
assertNotNull,传入非空,为空时抛出异常和信息
assertTrue,断言为真,如果为假(false)则抛出异常和信息
assertFalse,断言为假,如果为真(true)则抛出异常和信息
assertSame,引用同一对象,如果不是则抛出异常和信息
assertNotSame, 引用不同对象,如果是同一对象则抛出异常和信息

下面的例子的断言都是OK的,没有异常: