简体   繁体   中英

kotlin Extension function in assertj

I'm try to implement a extension function in my test with 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. unfortunately we use the java assertj, that's why I tried to implement a extension function.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM