Skip to content

Commit

Permalink
Add assertInstanceOf methods
Browse files Browse the repository at this point in the history
Added `assertInstanceOf` assertions with upcasting contracts

Issue: junit-team#1866
  • Loading branch information
awelless committed Aug 25, 2023
1 parent e427978 commit 544b4e1
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
Expand Up @@ -231,6 +231,71 @@ fun assertNotNull(actual: Any?, messageSupplier: () -> String) {
Assertions.assertNotNull(actual, messageSupplier)
}

/**
* Example usage:
* ```kotlin
* val string: Any = ...
*
* assertInstanceOf<String>(string)
*
* // compiler smart casts string to a String object
* assertTrue(string.isNotEmpty())
* ```
* @see Assertions.assertInstanceOf
*/
@API(since = "5.11", status = EXPERIMENTAL)
inline fun <reified T : Any> assertInstanceOf(actual: Any) {
contract {
returns() implies (actual is T)
}

Assertions.assertInstanceOf(T::class.java, actual)
}

/**
* Example usage:
* ```kotlin
* val string: Any = ...
*
* assertInstanceOf<String>(string, "Should be a String")
*
* // compiler smart casts string to a String object
* assertTrue(string.isNotEmpty())
* ```
* @see Assertions.assertInstanceOf
*/
@API(since = "5.11", status = EXPERIMENTAL)
inline fun <reified T : Any> assertInstanceOf(actual: Any, message: String) {
contract {
returns() implies (actual is T)
}

Assertions.assertInstanceOf(T::class.java, actual, message)
}

/**
* Example usage:
* ```kotlin
* val string: Any = ...
*
* assertInstanceOf<String>(string) { "Should be a String" }
*
* // compiler smart casts string to a String object
* assertTrue(string.isNotEmpty())
* ```
* @see Assertions.assertInstanceOf
*/
@API(since = "5.11", status = EXPERIMENTAL)
inline fun <reified T : Any> assertInstanceOf(actual: Any, noinline messageSupplier: () -> String) {
contract {
returns() implies (actual is T)

callsInPlace(messageSupplier, AT_MOST_ONCE)
}

Assertions.assertInstanceOf(T::class.java, actual, messageSupplier)
}

/**
* Example usage:
* ```kotlin
Expand Down
Expand Up @@ -228,6 +228,14 @@ class KotlinAssertionsTests {
// nullableString?.isEmpty()
}

@Test
fun `assertInstanceOf with compiler smart cast`() {
val string: Any = "string"

assertInstanceOf<String>(string)
assertFalse(string.isEmpty()) // smart cast to a String object
}

@Test
fun `assertDoesNotThrow with value initialization in lambda`() {
val value: Int
Expand Down

0 comments on commit 544b4e1

Please sign in to comment.