这是我的课堂考试:
private const val FAKE_STRING = "APP NAME"
@RunWith(MockitoJUnitRunner::class)
class UnitTestSample {
@Mock
private lateinit var mockContext: Context
@Test
fun readStringFromContext_LocalizedString() {
// Given a mocked Context injected into the object under test...
`when`(mockContext.getString(R.string.app_name))
.thenReturn(FAKE_STRING)
val myObjectUnderTest = ClassUnderTest(mockContext)
// ...when the string is returned from the object under test...
val result: String = myObjectUnderTest.getHelloWorldString()
// ...then the result should be the expected one.
assertThat(result, `is`(FAKE_STRING))
}
}
这是我的gradle.build.kt(Kotlin DSL)的一部分:
plugins {
id("com.android.application")
kotlin("android")
kotlin("kapt")
kotlin("android.extensions")
id("com.onesignal.androidsdk.onesignal-gradle-plugin")
jacoco
maven
}
dependencies {
...
//Test base
testImplementation("junit:junit:4.12")
testImplementation("org.junit.jupiter:junit-jupiter-api:5.0.3")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.0.3")
androidTestImplementation("androidx.test:runner:1.2.0")
androidTestImplementation("androidx.test.espresso:espresso-core:3.2.0")
//Unit Tests
testImplementation("org.mockito:mockito-core:3.0.0")
testImplementation("org.mockito:mockito-inline:3.0.0") //support for kotlin final classes
//Android UI Test
androidTestImplementation("org.robolectric:robolectric:3.7.1")
}
如您所见,Android Studio无法识别Mockito。我已经导入了org.mockito.junit.MockitoJUnitRunner
我正在运行此示例单元测试
src/test/java/.../UnitTestSample.kt
您对如何使其工作有任何想法吗?
编辑(解决方案):
我终于在评论部分的帮助下使其工作了。该问题是
答案 0 :(得分:1)
错误消息非常清楚:an annotation argument must be a compile time argument
。
所以问题可能出在相关依赖项的配置上-在编译时不可用。
答案 1 :(得分:0)
编辑:清理答案
对于JUnit5和Mockito,使用以下依赖项(或更新的)和范围:
testImplementation("org.junit.jupiter:junit-jupiter-api:5.4.2")
compile("org.junit.jupiter:junit-jupiter-engine:5.4.2")
testImplementation("org.mockito:mockito-core:3.0.0")
testImplementation("org.mockito:mockito-junit-jupiter:3.0.0")
testImplementation("org.mockito:mockito-inline:3.0.0")
在测试中,使用扩展而不是Runner(用于JUnit 4)。
@ExtendWith(MockitoExtension::class)
以5.0.3的JUnit 5依赖项运行时,出现以下错误,因此请考虑升级到较新的版本(如上面的依赖项所示)。
java.lang.NoSuchMethodError:
org.junit.platform.commons.support.AnnotationSupport.findAnnotation(Ljava/util/Optional;Ljava/lang/Class;)Ljava/util/Optional;
...
Suppressed: java.lang.NullPointerException
at org.mockito.junit.jupiter.MockitoExtension.afterEach(MockitoExtension.java:214)
为了实现从Maven到Gradle的转换,我使用了该网站 https://sagioto.github.io/maven2gradle/