Skip to content

Commit 3580f04

Browse files
authored
Add contracts to Kotlin-specific assertions (#3259)
* Introduce Kotlin-specific `assertNull` and `assertNotNull` methods * Introduce contracts for `assertNull`, `assertNotNull`, `assertThrows` and `assertDoesNotThrow` methods * Add examples to KotlinAssertionsDemo Resolves #1866.
1 parent 2f2dc33 commit 3580f04

File tree

5 files changed

+410
-16
lines changed

5 files changed

+410
-16
lines changed

documentation/src/docs/asciidoc/release-notes/release-notes-5.12.0-M1.adoc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ JUnit repository on GitHub.
4848
- A section containing JUnit-specific metadata about each test/container to the HTML
4949
report is now written by open-test-reporting when added to the classpath/module path
5050
- Information about published files is now included as attachments.
51+
* Introduced contracts for Kotlin-specific assertion methods.
5152

5253

5354
[[release-notes-5.12.0-M1-junit-jupiter]]

documentation/src/test/kotlin/example/KotlinAssertionsDemo.kt

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ import org.junit.jupiter.api.Tag
1919
import org.junit.jupiter.api.Test
2020
import org.junit.jupiter.api.assertAll
2121
import org.junit.jupiter.api.assertDoesNotThrow
22+
import org.junit.jupiter.api.assertInstanceOf
23+
import org.junit.jupiter.api.assertNotNull
2224
import org.junit.jupiter.api.assertThrows
2325
import org.junit.jupiter.api.assertTimeout
2426
import org.junit.jupiter.api.assertTimeoutPreemptively
@@ -107,5 +109,29 @@ class KotlinAssertionsDemo {
107109
Thread.sleep(100)
108110
}
109111
}
112+
113+
@Test
114+
fun `assertNotNull with a smart cast`() {
115+
val nullablePerson: Person? = person
116+
117+
assertNotNull(nullablePerson)
118+
119+
// The compiler smart casts nullablePerson to a non-nullable object.
120+
// The safe call operator (?.) isn't required.
121+
assertEquals(person.firstName, nullablePerson.firstName)
122+
assertEquals(person.lastName, nullablePerson.lastName)
123+
}
124+
125+
@Test
126+
fun `assertInstanceOf with a smart cast`() {
127+
val maybePerson: Any = person
128+
129+
assertInstanceOf<Person>(maybePerson)
130+
131+
// The compiler smart casts maybePerson to a Person object,
132+
// allowing to access the Person properties.
133+
assertEquals(person.firstName, maybePerson.firstName)
134+
assertEquals(person.lastName, maybePerson.lastName)
135+
}
110136
}
111137
// end::user_guide[]

0 commit comments

Comments
 (0)