|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
package example |
|
|
|
|
|
|
|
import example.domain.Person |
|
import example.util.Calculator |
|
import org.junit.jupiter.api.Assertions.assertEquals |
|
import org.junit.jupiter.api.Assertions.assertTrue |
|
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.assertThrows |
|
import org.junit.jupiter.api.assertTimeout |
|
import org.junit.jupiter.api.assertTimeoutPreemptively |
|
import java.time.Duration |
|
|
|
class KotlinAssertionsDemo { |
|
|
|
private val person = Person("Jane", "Doe") |
|
private val people = setOf(person, Person("John", "Doe")) |
|
|
|
@Test |
|
fun `exception absence testing`() { |
|
val calculator = Calculator() |
|
val result = assertDoesNotThrow("Should not throw an exception") { |
|
calculator.divide(0, 1) |
|
} |
|
assertEquals(0, result) |
|
} |
|
|
|
@Test |
|
fun `expected exception testing`() { |
|
val calculator = Calculator() |
|
val exception = assertThrows<ArithmeticException> ("Should throw an exception") { |
|
calculator.divide(1, 0) |
|
} |
|
assertEquals("/ by zero", exception.message) |
|
} |
|
|
|
@Test |
|
fun `grouped assertions`() { |
|
assertAll( |
|
"Person properties", |
|
{ assertEquals("Jane", person.firstName) }, |
|
{ assertEquals("Doe", person.lastName) } |
|
) |
|
} |
|
|
|
@Test |
|
fun `grouped assertions from a stream`() { |
|
assertAll( |
|
"People with first name starting with J", |
|
people |
|
.stream() |
|
.map { |
|
|
|
{ assertTrue(it.firstName.startsWith("J")) } |
|
} |
|
) |
|
} |
|
|
|
@Test |
|
fun `grouped assertions from a collection`() { |
|
assertAll( |
|
"People with last name of Doe", |
|
people.map { { assertEquals("Doe", it.lastName) } } |
|
) |
|
} |
|
|
|
|
|
@Tag("timeout") |
|
|
|
@Test |
|
fun `timeout not exceeded testing`() { |
|
val fibonacciCalculator = FibonacciCalculator() |
|
val result = assertTimeout(Duration.ofMillis(1000)) { |
|
fibonacciCalculator.fib(14) |
|
} |
|
assertEquals(377, result) |
|
} |
|
|
|
|
|
@Tag("timeout") |
|
@extensions.ExpectToFail |
|
|
|
@Test |
|
fun `timeout exceeded with preemptive termination`() { |
|
|
|
|
|
assertTimeoutPreemptively(Duration.ofMillis(10)) { |
|
|
|
Thread.sleep(100) |
|
} |
|
} |
|
} |
|
|
|
|