Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kotlin: Support `assertThat(foo) { isNotNull() isNotEqualTo(bar) ... }` #572

Open
cpovirk opened this issue Jun 10, 2019 · 5 comments

Comments

Projects
None yet
4 participants
@cpovirk
Copy link
Member

commented Jun 10, 2019

It's already possible to write nearly that by using apply:

assertThat(foo).apply {
  isNotNull()
  isNotEqualTo(bar)
}

Might it be worth a shortcut? Anecdotes welcome.

@cpovirk

This comment has been minimized.

Copy link
Member Author

commented Jun 10, 2019

I'm reliably informed that the implementation would be something like:

operator fun <T: Subject> T.invoke(assertions: T.() -> Unit): Unit = this.assertions()

@JakeWharton

This comment has been minimized.

Copy link
Member

commented Jun 10, 2019

Yep, that'll work!

I also flip the parameter to a receiver, but that requires one extension per subject type instead of the invoke trick.

@vRallev

This comment has been minimized.

Copy link

commented Jun 10, 2019

@JakeWharton Is this what you mean?

fun assertThat(string: String, assertions: StringSubject.() -> Unit) {
  assertThat(string).run { assertions() }
}

This would allow

assertThat("hello") {
  isNotEmpty()
  isEqualTo("hello")
}
@JakeWharton

This comment has been minimized.

Copy link
Member

commented Jun 10, 2019

No. The parameter becomes a receiver of the extension.

fun String.assertThat(assertions: StringSubject.() -> Unit) = assertThat(this).assertions()
@vRallev

This comment has been minimized.

Copy link

commented Jun 10, 2019

Got it. Then it reads differently, though. But that's a matter of taste I guess.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.