Manu Zi
Manu Zi

Reputation: 2370

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

Upvotes: 1

Views: 1646

Answers (2)

Manu Zi
Manu Zi

Reputation: 2370

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

Upvotes: 1

Mikezx6r
Mikezx6r

Reputation: 16905

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)

Upvotes: 1

Related Questions