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

Let assertions return their parameter on the happy path #91

Closed
MarkusAmshove opened this issue Jan 12, 2018 · 1 comment
Closed

Let assertions return their parameter on the happy path #91

MarkusAmshove opened this issue Jan 12, 2018 · 1 comment

Comments

@MarkusAmshove
Copy link
Owner

MarkusAmshove commented Jan 12, 2018

(came up in #90)

Some assertions should return their parameter back to the caller, to use them as a kind of verification in unit tests.

This will also make chaining assertions possible

theString
    .shouldNotBeNull()
    .shouldNotBeEmpty()

Example:

infix fun Any?.shouldBeInstanceOf(className: Class<*>) = assertTrue("Expected $this to be an instance of $className", className.isInstance(this))

to

inline fun <reified T: Any> Any.shouldBeInstanceOf() : T = if(this::class.isInstance(T::class)) this as T else throw AssertionError("Expected $this to be an instance of ${T::class.qualifiedName}")

which has to be a separate method to not break existing code.

This would allow:

open class Base {
    fun doSomething() = println("Base")
}

class Child : Base() {
    fun different() = println("Child")
}

fun main(args: Array<String>) {
    val base : Base = Child()
    // base.different() - Doesn't compile, not of type Child
    val child = base.shouldBeInstanceOf<Child>()
    child.different()
}

Currently identified assertions:

shouldBeInstanceOf
All numerical assertions in form of: shouldBeGreaterThan
All String and CharSequence assertions
The generic should method

@MarkusAmshove
Copy link
Owner Author

I've just released these changes with v1.34

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

1 participant