Android Studio 3.0 Canary 1:引用 Kotlin 类的 Kotlin 测试或 Java 测试失败
更新
此问题已在此处提交错误:https://youtrack.jetbrains.com/issue/KT-17951
更新 2
该错误已在Android Studio 3.0 Canary 3中修复
原始帖子
我刚刚开始玩Android Studio 3.0,我从一开始就启用了kotlin支持。我在我的项目中写了一个非常简单的Kotlin类:
data class Wallet(val coins: Int) {
fun add(value: Int): Wallet = Wallet(coins + value)
fun substract(value: Int): Wallet = if (coins > value) Wallet(coins + value) else throw InsufficientFundsException()
}
现在我想测试这个类,首先我在Kotlin中写了一个本地运行的unittest(测试目录):
class WalletTestKotlin {
@Throws(Exception::class)
@Test
fun add() {
Assert.assertEquals(22, Wallet(20).add(2).coins.toLong())
Assert.assertNotEquals(5, Wallet(2).add(13).coins.toLong())
}
}
它编译并运行,但出现错误消息:
类未找到: “com.agentknopf.hachi.repository.model.WalletTestKotlin”Empty test suite.
因此,我用Java重写了测试:
public class WalletTest {
@Throws(exceptionClasses = Exception.class)
@Test
public void add() {
Assert.assertEquals(22, new Wallet(20).add(2).getCoins());
Assert.assertNotEquals(5, new Wallet(2).add(13).getCoins());
}
}
然而,该测试也失败了 - 这次找不到Kotlin类“钱包”:
java.lang.NoClassDefFoundError: com/example/repository/model/Wallet
我想知道我是否错过了什么...运行 Java 测试,即不引用 Kotlin 类,而是引用 Java 类,仅成功完成。
我的项目 build.gradle 文件是默认文件:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.2-4'
repositories {
maven { url 'https://maven.google.com' }
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
maven { url 'https://maven.google.com' }
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
我的模块特定 build.gradle 的依赖项:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
//Kotlin support
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
//Testing libraries
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
testCompile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
}