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

Implemented 3353 GitHub issue #3374

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -77,5 +77,5 @@ JUnit repository on GitHub.
* ❓

==== New Features and Improvements

* ❓
* New `assertInstanceOf` methods added for Kotlin following up with similar Java `assertInstanceOf`
methods introduced in `5.8.0` version.
Expand Up @@ -19,6 +19,7 @@ import org.junit.jupiter.api.function.ThrowingSupplier
import java.time.Duration
import java.util.function.Supplier
import java.util.stream.Stream
import kotlin.reflect.KClass

/**
* @see Assertions.fail
Expand Down Expand Up @@ -110,6 +111,41 @@ inline fun <reified T : Throwable> assertThrows(executable: () -> Unit): T {
}
}

/**
* Example usage:
* ```kotlin
* assertInstanceOf(NotImplementedError(), Error::class)
* ```
*
* @see Assertions.assertInstanceOf
*/
@API(status = EXPERIMENTAL, since = "5.10")
fun assertInstanceOf(source: Any?, type: KClass<*>, message: String = "Provided source object is not of a given type $type") {
assert(type.isInstance(source), { message })
}

/**
* Example usage:
* ```kotlin
* assertThrows<AssertionError> {
* assertInstanceOf({ mapOf(Pair(1, 2)) }, MutableList::class)
* }
* assertEquals("Talk to a duck", exception.message)
* ```
* @see Assertions.assertInstanceOf
*/
@API(status = EXPERIMENTAL, since = "5.10")
inline fun assertInstanceOf(
sourceSupplier: () -> Any?,
type: KClass<*>,
message: String = "Provided function yield object that is not an instance of a given type $type"
) {
assert(
type.isInstance(sourceSupplier()),
{ message }
)
}

/**
* Example usage:
* ```kotlin
Expand Down
Expand Up @@ -184,6 +184,30 @@ class KotlinAssertionsTests {
)
)

@Test
fun `assertInstanceOf test passed`() {
assertInstanceOf(NotImplementedError(), Error::class)
}

@Test
fun `assertInstanceOf test negative`() {
assertThrows<AssertionError> {
assertInstanceOf(RuntimeException(), String::class)
}
}

@Test
fun `assertInstanceOf lazy test passed`() {
assertInstanceOf({ mutableListOf(1, 2, 3) }, List::class)
}

@Test
fun `assertInstanceOf lazy test negative`() {
assertThrows<AssertionError> {
assertInstanceOf({ mapOf(Pair(1, 2)) }, MutableList::class)
}
}

@Test
fun `assertAll with stream of functions that throw AssertionErrors`() {
val multipleFailuresError = assertThrows<MultipleFailuresError>("Should have thrown multiple errors") {
Expand Down