我似乎无法在Android Studio项目的Kotlin模块中访问测试包中的主类。请注意,下面显示的所有代码都在导入Android应用程序的Kotlin JVM模块中。
这是我的src/main/java
代码:
import com.google.gson.annotations.SerializedName
data class Customer(val password1: String,
val password2: String,
@SerializedName("last_name") val lastName: String,
@SerializedName("first_name") val firstName: String,
val email: String)
我在src/test/java
中的测试代码:
class CreateUser {
@Test
fun createRandomUser() {
val random = Random()
val randomNumber = random.nextInt(10000000)
val customer = Customer("password", "password", "lastName", "firstName", "ted$randomNumber@gmail.com")
}
}
我的build.gradle
代码如下所示:
buildscript {
ext.kotlin_version = '1.1.4-3'
repositories {
mavenCentral()
jcenter()
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.7.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'kotlin'
repositories {
mavenCentral()
jcenter()
}
dependencies {
// some other compile dependencies
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile "org.hamcrest:hamcrest-all:1.3"
testCompile 'junit:junit:4.11'
testCompile 'org.mockito:mockito-all:1.9.5'
testCompile "org.jetbrains.kotlin:kotlin-test"
testCompile "org.jetbrains.kotlin:kotlin-test-junit"
}
task javadocJar(type: Jar) {
classifier = 'javadoc'
from javadoc
}
task sourcesJar(type: Jar) {
classifier = 'sources'
from sourceSets.main.allSource
}
artifacts {
archives sourcesJar
archives javadocJar
}
compileKotlin {
kotlinOptions {
jvmTarget = "1.6"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "1.6"
}
}
根build.gradle
文件如下所示:
// Top-level build file where you can add configuration options
common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven {
url "https://jitpack.io"
credentials { username authToken }
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
versionName = "0.1.1"
rxJavaVersion = "2.1.3"
okHttpVersion = "3.9.0"
retrofitVersion = "2.3.0"
rxJava2AdapterVersion = "1.0.0"
googleGsonVersion = "2.8.0"
}
我得到的错误是gradle无法解析Test类中的Customer
(Unresolved reference: Customer
)。它似乎没有将主类包含到测试源目录中。然而,它在IDE中解决了。
答案 0 :(得分:2)
好的,我找到了解决方案。我似乎必须在build.gradle中明确指定src文件夹,并将所有Kotlin代码分别放在src/main/kotlin
和src/test/kotlin
中。
sourceSets {
main.kotlin.srcDirs = ['src/main/kotlin', 'src/main/java']
main.java.srcDirs = []
test.kotlin.srcDirs = ['src/test/kotlin', 'src/test/java']
test.java.srcDirs = ['src/test/kotlin', 'src/test/java']
}
一旦我这样做了,测试开始按预期工作 - 甚至在Jenkins上生成了报告,这很棒。