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

Add function reference support for use with shouldThrow #111

Open
aerb opened this issue Jun 23, 2018 · 2 comments
Open

Add function reference support for use with shouldThrow #111

aerb opened this issue Jun 23, 2018 · 2 comments

Comments

@aerb
Copy link

aerb commented Jun 23, 2018

As an alternative syntax to:

val theFunction = { myThrowingFunction() }

// Expect any exception
theFunction shouldThrow AnyException

It would be really nice to add function reference syntax such as:

::myThrowingFunction shouldThrow AnyException

If the function takes in an argument it would then be:

::myThrowingFunction providedWith "some argument" shouldThrow AnyException

I've hacked these implementations in my own project as:

fun <R: Throwable> KFunction0<R>.shouldThrow(expectedException: KClass<R>) {
    val f = { this }
    f.shouldThrow(expectedException)
}

infix fun <P1, R> KFunction1<P1, R>.providedWith(arg: P1): () -> Any? = {
    this.invoke(arg)
}

I would be happy to clean it up, and submit a formal PR if this sort of feature interests you.

Thanks!

@aerb
Copy link
Author

aerb commented Jun 23, 2018

An alternate, simpler approach could be to introduce a wrapper function that returns a lambda for use with shouldThrow.

For example:

invoking { myThrowingFunction() } shouldThrow AnyException

fun invoking(f: () -> Unit): () -> Unit = f

I guess ultimately what I'm trying to avoid is having to define a local interim variable that is then passed to shouldThrow. I think one of these two approaches would avoid some of the variable noise in tests.

@MarkusAmshove
Copy link
Owner

I really like that idea, as it reduces the noise in tests.

Can the providedWith function work with an arbitrary number of parameters?
If not I would prever the second version.
The second version also doesn't abstract away the function call which makes it a bit clearer what is tested.
If you like, send a PR 👍

rubengees added a commit to rubengees/Kluent that referenced this issue Jan 26, 2019
This implements the second proposal in MarkusAmshove#111. The tests have been
adjusted to showcase the new syntax.
rubengees added a commit to rubengees/Kluent that referenced this issue Jan 26, 2019
This implements the second proposal in MarkusAmshove#111. The tests have been
adjusted to showcase the new syntax.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants