Skip to content

Commit

Permalink
Add contracts to Kotlin-specific assertions (#3259)
Browse files Browse the repository at this point in the history
* Introduce Kotlin-specific `assertNull` and `assertNotNull` methods
* Introduce contracts for `assertNull`, `assertNotNull`, `assertThrows` 
  and `assertDoesNotThrow` methods
* Add examples to KotlinAssertionsDemo

Resolves #1866.
  • Loading branch information
awelless authored Dec 5, 2024
1 parent 2f2dc33 commit 3580f04
Show file tree
Hide file tree
Showing 5 changed files with 410 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ JUnit repository on GitHub.
- A section containing JUnit-specific metadata about each test/container to the HTML
report is now written by open-test-reporting when added to the classpath/module path
- Information about published files is now included as attachments.
* Introduced contracts for Kotlin-specific assertion methods.


[[release-notes-5.12.0-M1-junit-jupiter]]
Expand Down
26 changes: 26 additions & 0 deletions documentation/src/test/kotlin/example/KotlinAssertionsDemo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertAll
import org.junit.jupiter.api.assertDoesNotThrow
import org.junit.jupiter.api.assertInstanceOf
import org.junit.jupiter.api.assertNotNull
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.assertTimeout
import org.junit.jupiter.api.assertTimeoutPreemptively
Expand Down Expand Up @@ -107,5 +109,29 @@ class KotlinAssertionsDemo {
Thread.sleep(100)
}
}

@Test
fun `assertNotNull with a smart cast`() {
val nullablePerson: Person? = person

assertNotNull(nullablePerson)

// The compiler smart casts nullablePerson to a non-nullable object.
// The safe call operator (?.) isn't required.
assertEquals(person.firstName, nullablePerson.firstName)
assertEquals(person.lastName, nullablePerson.lastName)
}

@Test
fun `assertInstanceOf with a smart cast`() {
val maybePerson: Any = person

assertInstanceOf<Person>(maybePerson)

// The compiler smart casts maybePerson to a Person object,
// allowing to access the Person properties.
assertEquals(person.firstName, maybePerson.firstName)
assertEquals(person.lastName, maybePerson.lastName)
}
}
// end::user_guide[]
Loading

0 comments on commit 3580f04

Please sign in to comment.