assertj 中的 kotlin 扩展函数

kotlin Extension function in assertj

我正在尝试使用 assertj 在我的测试中实现一个扩展函数。我有一个这样的自定义异常:

class MyException: Exception {
        constructor(message: String, code: Int) : super(message)
        constructor(cause: Throwable, code: Int) : super(cause)
}

我想在我的测试中检查 属性 code。不幸的是我们使用了 java assertj,这就是我尝试实现扩展功能的原因。

我有以下内容,我的测试:

@Test
fun `Creating webdto without name fails`() {
    assertThatExceptionOfType(MyException::class.java)
            .isThrownBy { service.create(WebDto.apply { this.name = null }) }
            .withMessageContaining("Bean validation error.")
            .withErrorCodeContaining(1) // extension function
}

private fun <T : Throwable?> ThrowableAssertAlternative<T>.withErrorCodeContaining(expectedErrorCode: ErrorCode): ThrowableAssertAlternative<T> {
    // How can I access the actual or delegate parameter?
    return this
}

我没有机会在 withErrorCodeContaining

中获取 actualdelegate 参数

有什么想法吗?提前谢谢你

不完全是您想要的,但会实现您想要的。

根据文档 https://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion,您可以使用

val thrown: MyException = (MyException)catchThrowable { 
    service.create(WebDto.apply { this.name = null })
} as MyException

assertThat(thrown.message).isEqualTo("Bean validation error.")
assertThat(thrown.code).isEqualTo(1)
fun <T : MyException?> ThrowableAssertAlternative<T>.withErrorCodeContaining(expectedErrorCode: Int):
    ThrowableAssertAlternative<T> = this.matches({ it?.code == expectedErrorCode },
        "ErrorCode from the RestApiException doesn't match with the expected: <\"$expectedErrorCode\">")

这是我一直努力并期望得到的解决方案