测试包不读取主包中定义的Kotlin类

我似乎无法访问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类中的CustomerUnresolved reference: Customer )。 它似乎没有将主类包括到测试源目录中。 然而,它在IDE中解决。

好的,我找到了解决办法。 看来我必须在build.gradle中明确指定src文件夹,并将所有Kotlin代码分别放在src/main/kotlinsrc/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'] } 

一旦我这样做,测试开始按预期工作 – 报告甚至生成在詹金斯是伟大的。