【发布时间】:2020-04-25 06:17:10
【问题描述】:
我正在尝试在 Android 中使用 Mockito 和 Kotlin 运行 Instrumentation 测试 (androidTest)。
- 我的依赖项中有核心库。
'org.mockito:mockito-core:3.3.3' - 我的项目是用
Kotlin编写的,所以我已经org.mockito:mockito-inline:3.3.3来解决final class 问题。 - 因为我想在
Android中运行模拟,所以我的依赖项中也有org.mockito:mockito-android:3.3.3。
但在编译代码时出现以下错误
发现多个文件具有独立于操作系统的路径 'mockito-extensions/org.mockito.plugins.MockMaker'
这是重现该问题的示例测试代码。将此测试作为仪器测试运行。 (androidTest)。
MainActivityTest
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
class Calculator {
fun add(x: Int, y: Int): Int {
return x + y
}
}
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@Mock
lateinit var calculator: Calculator
@Before
fun before() {
MockitoAnnotations.initMocks(this)
}
@Test
fun test() {
`when`(calculator.add(10, 10)).thenReturn(20)
assertEquals(calculator.add(10, 10), 20)
}
}
app/build.gradle
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
}
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.theapache64.mockitosample"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
testOptions {
unitTests.returnDefaultValues = true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'org.mockito:mockito-core:3.3.3'
androidTestImplementation 'org.mockito:mockito-android:3.3.3'
androidTestImplementation 'org.mockito:mockito-inline:3.3.3'
}
难道不能使用Kotlin 和Mockito 运行Android instrumentation test 吗?
注意:如果您认为这是一个重复的问题,我已经在整个互联网上进行了搜索。类似的堆栈跟踪还有其他问题,但我的情况不同。
任何帮助将不胜感激
【问题讨论】: