Skip to content

Commit

Permalink
Add Kotlin friendly assertInstanceOf assertions
Browse files Browse the repository at this point in the history
Resolves #3353

Signed-off-by: Björn Michael <b.michael@gmx.de>
  • Loading branch information
bjmi committed Dec 30, 2023
1 parent 14114f5 commit bedba01
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
Expand Up @@ -50,7 +50,8 @@ JUnit repository on GitHub.
* Improved Javadoc for `Assertions.assertTimeoutPreemptively` regarding thread interrupt.
* Documentation for `@Disabled` and conditional annotations now explicitly explains that
such annotations are not inherited by subclasses.

* New `assertInstanceOf` methods added for Kotlin following up with similar Java
`assertInstanceOf` methods introduced in `5.8` version.

[[release-notes-5.10.1-junit-vintage]]
=== JUnit Vintage
Expand Down
Expand Up @@ -287,3 +287,23 @@ fun <R> assertTimeoutPreemptively(timeout: Duration, message: String, executable
@API(status = EXPERIMENTAL, since = "5.5")
fun <R> assertTimeoutPreemptively(timeout: Duration, message: () -> String, executable: () -> R): R =
Assertions.assertTimeoutPreemptively(timeout, executable, message)

/**
* Example usage:
* ```kotlin
* assertInstanceOf<RandomAccess>(list, "List should support fast random access")
* ```
* @see Assertions.assertInstanceOf
* @since 5.10.1
*/
@API(status = EXPERIMENTAL, since = "5.10.1")
inline fun <reified T : Any> assertInstanceOf(actualValue: Any?, message: String? = null): T =
Assertions.assertInstanceOf(T::class.java, actualValue, message)

/*
* @see Assertions.assertInstanceOf
* @since 5.10.1
*/
@API(status = EXPERIMENTAL, since = "5.10.1")
inline fun <reified T : Any> assertInstanceOf(actualValue: Any?, noinline message: () -> String): T =
Assertions.assertInstanceOf(T::class.java, actualValue, message)
Expand Up @@ -211,6 +211,29 @@ class KotlinAssertionsTests {
assertMessageStartsWith(error, assertionMessage)
}

@Test
fun assertInstanceOf() {
assertInstanceOf<RandomAccess>(listOf("whatever"))
assertInstanceOf<RandomAccess>(listOf("whatever"), "No random access")
assertInstanceOf<RandomAccess>(listOf("whatever")) { "No random access" }
}

@Test
fun `assertInstanceOf fails wrong type value`() {
val result = assertThrows<AssertionError> {
assertInstanceOf<String>(StringBuilder(), "Should be a String")
}
assertMessageStartsWith(result, "Should be a String")
}

@Test
fun `assertInstanceOf fails null value`() {
val result = assertThrows<AssertionError> {
assertInstanceOf<String>(null, "Should be a String")
}
assertMessageStartsWith(result, "Should be a String")
}

companion object {
fun assertExpectedExceptionTypes(
multipleFailuresError: MultipleFailuresError,
Expand Down

0 comments on commit bedba01

Please sign in to comment.