You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin Native单元测试断言失败栈跟踪无法正确显示源码行号

解决Kotlin Native测试栈跟踪无源代码行号问题

问题现象

运行Kotlin Native测试失败时,错误栈跟踪无法显示正确的源代码行号,取而代之的是无效信息:

kotlin.AssertionError: Expected value to be false.
    at kotlin.Throwable#<init>(Unknown Source)
    at kotlin.Error#<init>(Unknown Source)
    at kotlin.AssertionError#<init>(Unknown Source)
    at kotlin.test.DefaultAsserter#fail(Unknown Source)
xxx.TempTest.helloWorld FAILED
      kotlin.AssertionError at null:-1

解决方案

问题根源在于Kotlin Native测试二进制默认未生成调试符号,需在Gradle配置中为测试二进制开启调试模式,确保编译器输出源代码关联信息。

修改后的build.gradle.kts配置

plugins {
    kotlin("multiplatform") version "1.8.10"
}

// ... group and version declaration

repositories {
    mavenCentral()
}

kotlin {
    val hostOs = System.getProperty("os.name")
    val isMingwX64 = hostOs.startsWith("Windows")
    val nativeTarget = when {
        hostOs == "Mac OS X" -> macosX64("native")
        hostOs == "Linux" -> linuxX64("native")
        isMingwX64 -> mingwX64("native")
        else -> throw GradleException("Host OS is not supported in Kotlin/Native.")
    }

    nativeTarget.apply {
        binaries {
            executable {
                entryPoint = "main"
            }
            // 新增测试二进制配置,开启调试符号生成
            test {
                debuggable = true
                buildType = org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType.DEBUG
            }
        }
    }

    sourceSets {
        val commonMain by getting
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test"))
            }
        }
        val nativeMain by getting
        val nativeTest by getting

        nativeMain.dependsOn(commonMain)
    }
}

说明

通过在nativeTarget.binaries中添加test块并设置debuggable = true,强制编译器为测试二进制生成完整的调试符号。调试符号包含源代码行号、文件路径等信息,错误栈跟踪就能正确关联到测试代码的具体位置。

内容的提问来源于stack exchange,提问作者leung018

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:30:39