[英]kotlin Extension function in assertj
I'm try to implement a extension function in my test with assertj. 我尝试在我的测试中使用assertj实现扩展功能。 I have a custom exception like this: 我有一个这样的自定义异常:
class MyException: Exception {
constructor(message: String, code: Int) : super(message)
constructor(cause: Throwable, code: Int) : super(cause)
}
I would like to check the property code
in my test. 我想在测试中检查属性code
。 unfortunately we use the java assertj, that's why I tried to implement a extension function. 不幸的是,我们使用了Java assertj,这就是为什么我尝试实现扩展功能的原因。
I have the following, my test: 我的测试如下:
@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
}
I have no chance to get the actual
or delegate
parameter in my withErrorCodeContaining
我没有机会在withErrorCodeContaining
获取actual
或delegate
参数
Any ideas? 有任何想法吗? thank you in advance 先感谢您
Not exactly what you're looking for, but will accomplish what you want. 并不是您要找的东西,而是可以实现您想要的东西。
As per docs https://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html#exception-assertion , you can use 根据文档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\">")
That's the solution I've worked for and expected 这是我一直努力并期望的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.