|
| 1 | +package com.baeldung.kotlin.junit5 |
| 2 | + |
| 3 | +import org.junit.jupiter.api.* |
| 4 | +import org.junit.jupiter.api.function.Executable |
| 5 | + |
| 6 | +class CalculatorTest5 { |
| 7 | + private val calculator = Calculator() |
| 8 | + |
| 9 | + @Test |
| 10 | + fun testAddition() { |
| 11 | + Assertions.assertEquals(4, calculator.add(1, 3)) |
| 12 | + } |
| 13 | + |
| 14 | + @Test |
| 15 | + fun testDivideByZero() { |
| 16 | + val exception = Assertions.assertThrows(DivideByZeroException::class.java) { |
| 17 | + calculator.divide(5, 0) |
| 18 | + } |
| 19 | + |
| 20 | + Assertions.assertEquals(5, exception.numerator) |
| 21 | + } |
| 22 | + |
| 23 | + @Test |
| 24 | + fun testSquares() { |
| 25 | + Assertions.assertAll( |
| 26 | + Executable { Assertions.assertEquals(1, calculator.square(1)) }, |
| 27 | + Executable { Assertions.assertEquals(4, calculator.square(2)) }, |
| 28 | + Executable { Assertions.assertEquals(9, calculator.square(3)) } |
| 29 | + ) |
| 30 | + } |
| 31 | + |
| 32 | + @TestFactory |
| 33 | + fun testSquaresFactory() = listOf( |
| 34 | + DynamicTest.dynamicTest("1 squared") { Assertions.assertEquals(1,calculator.square(1))}, |
| 35 | + DynamicTest.dynamicTest("2 squared") { Assertions.assertEquals(4,calculator.square(2))}, |
| 36 | + DynamicTest.dynamicTest("3 squared") { Assertions.assertEquals(9,calculator.square(3))} |
| 37 | + ) |
| 38 | + |
| 39 | + @TestFactory |
| 40 | + fun testSquaresFactory2() = listOf( |
| 41 | + 1 to 1, |
| 42 | + 2 to 4, |
| 43 | + 3 to 9, |
| 44 | + 4 to 16, |
| 45 | + 5 to 25) |
| 46 | + .map { (input, expected) -> |
| 47 | + DynamicTest.dynamicTest("$input squared") { |
| 48 | + Assertions.assertEquals(expected, calculator.square(input)) |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + private val squaresTestData = listOf( |
| 53 | + 1 to 1, |
| 54 | + 2 to 4, |
| 55 | + 3 to 9, |
| 56 | + 4 to 16, |
| 57 | + 5 to 25) |
| 58 | + |
| 59 | + @TestFactory |
| 60 | + fun testSquaresFactory3() = squaresTestData |
| 61 | + .map { (input, expected) -> |
| 62 | + DynamicTest.dynamicTest("$input squared") { |
| 63 | + Assertions.assertEquals(expected, calculator.square(input)) |
| 64 | + } |
| 65 | + } |
| 66 | + @TestFactory |
| 67 | + fun testSquareRootsFactory3() = squaresTestData |
| 68 | + .map { (expected, input) -> |
| 69 | + DynamicTest.dynamicTest("Square root of $input") { |
| 70 | + Assertions.assertEquals(expected.toDouble(), calculator.squareRoot(input)) |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + @Tags( |
| 75 | + Tag("slow"), |
| 76 | + Tag("logarithms") |
| 77 | + ) |
| 78 | + @Test |
| 79 | + fun testLogarithms() { |
| 80 | + Assertions.assertEquals(3.0, calculator.log(2, 8)) |
| 81 | + } |
| 82 | +} |
0 commit comments