JAVA-101 Split Core Kotlin

This commit is contained in:
mikr
2020-06-08 00:22:04 +02:00
parent 0130ae560f
commit 73e169d1eb
48 changed files with 136 additions and 27 deletions

View File

@@ -7,13 +7,5 @@ This module contains articles about Kotlin core features.
- [Kotlin Java Interoperability](https://www.baeldung.com/kotlin-java-interoperability)
- [Get a Random Number in Kotlin](https://www.baeldung.com/kotlin-random-number)
- [Create a Java and Kotlin Project with Maven](https://www.baeldung.com/kotlin-maven-java-project)
- [Guide to Sorting in Kotlin](https://www.baeldung.com/kotlin-sort)
- [Creational Design Patterns in Kotlin: Builder](https://www.baeldung.com/kotlin-builder-pattern)
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
- [Implementing a Binary Tree in Kotlin](https://www.baeldung.com/kotlin-binary-tree)
- [JUnit 5 for Kotlin Developers](https://www.baeldung.com/junit-5-kotlin)
- [Converting Kotlin Data Class from JSON using GSON](https://www.baeldung.com/kotlin-json-convert-data-class)
- [Fuel HTTP Library with Kotlin](https://www.baeldung.com/kotlin-fuel)
- [Introduction to Kovenant Library for Kotlin](https://www.baeldung.com/kotlin-kovenant)
- [Dependency Injection for Kotlin with Injekt](https://www.baeldung.com/kotlin-dependency-injection-with-injekt)
- [[More --> ]](/core-kotlin-modules/core-kotlin-2)
- [Kotlin Ternary Conditional Operator](https://www.baeldung.com/kotlin-ternary-operator)
- [Sequences in Kotlin](https://www.baeldung.com/kotlin/sequences)

View File

@@ -1,19 +0,0 @@
package com.baeldung.binarytree
/**
* Example of how to use the {@link Node} class.
*
*/
fun main(args: Array<String>) {
val tree = Node(4)
val keys = arrayOf(8, 15, 21, 3, 7, 2, 5, 10, 2, 3, 4, 6, 11)
for (key in keys) {
tree.insert(key)
}
val node = tree.find(4)!!
println("Node with value ${node.key} [left = ${node.left?.key}, right = ${node.right?.key}]")
println("Delete node with key = 3")
node.delete(3)
print("Tree content after the node elimination: ")
println(tree.visit().joinToString { it.toString() })
}

View File

@@ -1,167 +0,0 @@
package com.baeldung.binarytree
/**
* An ADT for a binary search tree.
* Note that this data type is neither immutable nor thread safe.
*/
class Node(
var key: Int,
var left: Node? = null,
var right: Node? = null) {
/**
* Return a node with given value. If no such node exists, return null.
* @param value
*/
fun find(value: Int): Node? = when {
this.key > value -> left?.find(value)
this.key < value -> right?.find(value)
else -> this
}
/**
* Insert a given value into the tree.
* After insertion, the tree should contain a node with the given value.
* If the tree already contains the given value, nothing is performed.
* @param value
*/
fun insert(value: Int) {
if (value > this.key) {
if (this.right == null) {
this.right = Node(value)
} else {
this.right?.insert(value)
}
} else if (value < this.key) {
if (this.left == null) {
this.left = Node(value)
} else {
this.left?.insert(value)
}
}
}
/**
* Delete the value from the given tree. If the tree does not contain the value, the tree remains unchanged.
* @param value
*/
fun delete(value: Int) {
when {
value > key -> scan(value, this.right, this)
value < key -> scan(value, this.left, this)
else -> removeNode(this, null)
}
}
/**
* Scan the tree in the search of the given value.
* @param value
* @param node sub-tree that potentially might contain the sought value
* @param parent node's parent
*/
private fun scan(value: Int, node: Node?, parent: Node?) {
if (node == null) {
System.out.println("value " + value
+ " seems not present in the tree.")
return
}
when {
value > node.key -> scan(value, node.right, node)
value < node.key -> scan(value, node.left, node)
value == node.key -> removeNode(node, parent)
}
}
/**
* Remove the node.
*
* Removal process depends on how many children the node has.
*
* @param node node that is to be removed
* @param parent parent of the node to be removed
*/
private fun removeNode(node: Node, parent: Node?) {
node.left?.let { leftChild ->
run {
node.right?.let {
removeTwoChildNode(node)
} ?: removeSingleChildNode(node, leftChild)
}
} ?: run {
node.right?.let { rightChild -> removeSingleChildNode(node, rightChild) } ?: removeNoChildNode(node, parent)
}
}
/**
* Remove the node without children.
* @param node
* @param parent
*/
private fun removeNoChildNode(node: Node, parent: Node?) {
parent?.let { p ->
if (node == p.left) {
p.left = null
} else if (node == p.right) {
p.right = null
}
} ?: throw IllegalStateException(
"Can not remove the root node without child nodes")
}
/**
* Remove a node that has two children.
*
* The process of elimination is to find the biggest key in the left sub-tree and replace the key of the
* node that is to be deleted with that key.
*/
private fun removeTwoChildNode(node: Node) {
val leftChild = node.left!!
leftChild.right?.let {
val maxParent = findParentOfMaxChild(leftChild)
maxParent.right?.let {
node.key = it.key
maxParent.right = null
} ?: throw IllegalStateException("Node with max child must have the right child!")
} ?: run {
node.key = leftChild.key
node.left = leftChild.left
}
}
/**
* Return a node whose right child contains the biggest value in the given sub-tree.
* Assume that the node n has a non-null right child.
*
* @param n
*/
private fun findParentOfMaxChild(n: Node): Node {
return n.right?.let { r -> r.right?.let { findParentOfMaxChild(r) } ?: n }
?: throw IllegalArgumentException("Right child must be non-null")
}
/**
* Remove a parent that has only one child.
* Removal is effectively is just coping the data from the child parent to the parent parent.
* @param parent Node to be deleted. Assume that it has just one child
* @param child Assume it is a child of the parent
*/
private fun removeSingleChildNode(parent: Node, child: Node) {
parent.key = child.key
parent.left = child.left
parent.right = child.right
}
fun visit(): Array<Int> {
val a = left?.visit() ?: emptyArray()
val b = right?.visit() ?: emptyArray()
return a + arrayOf(key) + b
}
}

View File

@@ -1,22 +0,0 @@
package com.baeldung.builder
class FoodOrder private constructor(
val bread: String?,
val condiments: String?,
val meat: String?,
val fish: String?
) {
data class Builder(
var bread: String? = null,
var condiments: String? = null,
var meat: String? = null,
var fish: String? = null) {
fun bread(bread: String) = apply { this.bread = bread }
fun condiments(condiments: String) = apply { this.condiments = condiments }
fun meat(meat: String) = apply { this.meat = meat }
fun fish(fish: String) = apply { this.fish = fish }
fun build() = FoodOrder(bread, condiments, meat, fish)
}
}

View File

@@ -1,8 +0,0 @@
package com.baeldung.builder
class FoodOrderApply {
var bread: String? = null
var condiments: String? = null
var meat: String? = null
var fish: String? = null
}

View File

@@ -1,7 +0,0 @@
package com.baeldung.builder
data class FoodOrderNamed(
val bread: String? = null,
val condiments: String? = null,
val meat: String? = null,
val fish: String? = null)

View File

@@ -1,9 +0,0 @@
package com.baeldung.builder
fun main(args: Array<String>) {
FoodOrder.Builder()
.bread("bread")
.condiments("condiments")
.meat("meat")
.fish("bread").let { println(it) }
}

View File

@@ -1,25 +0,0 @@
package com.baeldung.scope
data class Student(var studentId: String = "", var name: String = "", var surname: String = "") {
}
data class Teacher(var teacherId: Int = 0, var name: String = "", var surname: String = "") {
fun setId(anId: Int): Teacher = apply { teacherId = anId }
fun setName(aName: String): Teacher = apply { name = aName }
fun setSurname(aSurname: String): Teacher = apply { surname = aSurname }
}
data class Headers(val headerInfo: String)
data class Response(val headers: Headers)
data class RestClient(val url: String) {
fun getResponse() = Response(Headers("some header info"))
}
data class BankAccount(val id: Int) {
fun checkAuthorization(username: String) = Unit
fun addPayee(payee: String) = Unit
fun makePayment(paymentDetails: String) = Unit
}

View File

@@ -1,42 +0,0 @@
package com.baeldung.sorting
fun sortMethodUsage() {
val sortedValues = mutableListOf(1, 2, 7, 6, 5, 6)
sortedValues.sort()
println(sortedValues)
}
fun sortByMethodUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortBy { it.second }
println(sortedValues)
}
fun sortWithMethodUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to "b", 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortWith(compareBy({it.second}, {it.first}))
println(sortedValues)
}
fun <T : kotlin.Comparable<T>> getSimpleComparator() : Comparator<T> {
val ascComparator = naturalOrder<T>()
return ascComparator
}
fun getComplexComparator() {
val complexComparator = compareBy<Pair<Int, String>>({it.first}, {it.second})
}
fun nullHandlingUsage() {
val sortedValues = mutableListOf(1 to "a", 2 to null, 7 to "c", 6 to "d", 5 to "c", 6 to "e")
sortedValues.sortWith(nullsLast(compareBy { it.second }))
println(sortedValues)
}
fun extendedComparatorUsage() {
val students = mutableListOf(21 to "Helen", 21 to "Tom", 20 to "Jim")
val ageComparator = compareBy<Pair<Int, String?>> {it.first}
val ageAndNameComparator = ageComparator.thenByDescending {it.second}
println(students.sortedWith(ageAndNameComparator))
}

View File

@@ -1,320 +0,0 @@
package com.baeldung.binarytree
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
class NodeTest {
@Before
fun setUp() {
}
@After
fun tearDown() {
}
/**
* Test suit for finding the node by value
* Partition the tests as follows:
* 1. tree depth: 0, 1, > 1
* 2. pivot depth location: not present, 0, 1, 2, > 2
*/
/**
* Find the node by value
* 1. tree depth: 0
* 2. pivot depth location: not present
*/
@Test
fun givenDepthZero_whenPivotNotPresent_thenNull() {
val n = Node(1)
assertNull(n.find(2))
}
/**
* Find the node by value
* 1. tree depth: 0
* 2. pivot depth location: 0
*/
@Test
fun givenDepthZero_whenPivotDepthZero_thenReturnNodeItself() {
val n = Node(1)
assertEquals(n, n.find(1))
}
/**
* Find the node by value
* 1. tree depth: 1
* 2. pivot depth location: not present
*/
@Test
fun givenDepthOne_whenPivotNotPresent_thenNull() {
val n = Node(1, Node(0))
assertNull(n.find(2))
}
/**
* Find the node by value
* 1. tree depth: 1
* 2. pivot depth location: not present
*/
@Test
fun givenDepthOne_whenPivotAtDepthOne_thenSuccess() {
val n = Node(1, Node(0))
assertEquals(n.left, n.find(0)
)
}
@Test
fun givenDepthTwo_whenPivotAtDepth2_then_Success() {
val left = Node(1, Node(0), Node(2))
val right = Node(5, Node(4), Node(6))
val n = Node(3, left, right)
assertEquals(left.left, n.find(0))
}
/**
* Test suit for inserting a value
* Partition the test as follows:
* 1. tree depth: 0, 1, 2, > 2
* 2. depth to insert: 0, 1, > 1
* 3. is duplicate: no, yes
* 4. sub-tree: left, right
*/
/**
* Test for inserting a value
* 1. tree depth: 0
* 2. depth to insert: 1
* 3. is duplicate: no
* 4. sub-tree: right
*/
@Test
fun givenTreeDepthZero_whenInsertNoDuplicateToRight_thenAddNode() {
val n = Node(1)
n.insert(2)
assertEquals(1, n.key)
with(n.right!!) {
assertEquals(2, key)
assertNull(left)
assertNull(right)
}
assertNull(n.left)
}
/**
* Test for inserting a value
* 1. tree depth: 0
* 2. depth to insert: 1
* 3. is duplicate: no
* 4. sub-tree: right
*/
@Test
fun givenTreeDepthZero_whenInsertNoDuplicateToLeft_thenSuccess() {
val n = Node(1)
n.insert(0)
assertEquals(1, n.key)
with(n.left!!) {
assertEquals(0, key)
assertNull(left)
assertNull(right)
}
assertNull(n.right)
}
/**
* Test for inserting a value
* 1. tree depth: 0
* 2. depth to insert: 1
* 3. is duplicate: yes
*/
@Test
fun givenTreeDepthZero_whenInsertDuplicate_thenSuccess() {
val n = Node(1)
n.insert(1)
assertEquals(1, n.key)
assertNull(n.right)
assertNull(n.left)
}
/**
* Test suit for inserting a value
* Partition the test as follows:
* 1. tree depth: 0, 1, 2, > 2
* 2. depth to insert: 0, 1, > 1
* 3. is duplicate: no, yes
* 4. sub-tree: left, right
*/
/**
* Test for inserting a value
* 1. tree depth: 1
* 2. depth to insert: 1
* 3. is duplicate: no
* 4. sub-tree: right
*/
@Test
fun givenTreeDepthOne_whenInsertNoDuplicateToRight_thenSuccess() {
val n = Node(10, Node(3))
n.insert(15)
assertEquals(10, n.key)
with(n.right!!) {
assertEquals(15, key)
assertNull(left)
assertNull(right)
}
with(n.left!!) {
assertEquals(3, key)
assertNull(left)
assertNull(right)
}
}
/**
* Test for inserting a value
* 1. tree depth: 1
* 2. depth to insert: 1
* 3. is duplicate: no
* 4. sub-tree: left
*/
@Test
fun givenTreeDepthOne_whenInsertNoDuplicateToLeft_thenAddNode() {
val n = Node(10, null, Node(15))
n.insert(3)
assertEquals(10, n.key)
with(n.right!!) {
assertEquals(15, key)
assertNull(left)
assertNull(right)
}
with(n.left!!) {
assertEquals(3, key)
assertNull(left)
assertNull(right)
}
}
/**
* Test for inserting a value
* 1. tree depth: 1
* 2. depth to insert: 1
* 3. is duplicate: yes
*/
@Test
fun givenTreeDepthOne_whenInsertDuplicate_thenNoChange() {
val n = Node(10, null, Node(15))
n.insert(15)
assertEquals(10, n.key)
with(n.right!!) {
assertEquals(15, key)
assertNull(left)
assertNull(right)
}
assertNull(n.left)
}
/**
* Test suit for removal
* Partition the input as follows:
* 1. tree depth: 0, 1, 2, > 2
* 2. value to delete: absent, present
* 3. # child nodes: 0, 1, 2
*/
/**
* Test for removal value
* 1. tree depth: 0
* 2. value to delete: absent
*/
@Test
fun givenTreeDepthZero_whenValueAbsent_thenNoChange() {
val n = Node(1)
n.delete(0)
assertEquals(1, n.key)
assertNull(n.left)
assertNull(n.right)
}
/**
* Test for removal
* 1. tree depth: 1
* 2. value to delete: absent
*/
@Test
fun givenTreeDepthOne_whenValueAbsent_thenNoChange() {
val n = Node(1, Node(0), Node(2))
n.delete(3)
assertEquals(1, n.key)
assertEquals(2, n.right!!.key)
with(n.left!!) {
assertEquals(0, key)
assertNull(left)
assertNull(right)
}
with(n.right!!) {
assertNull(left)
assertNull(right)
}
}
/**
* Test suit for removal
* 1. tree depth: 1
* 2. value to delete: present
* 3. # child nodes: 0
*/
@Test
fun givenTreeDepthOne_whenNodeToDeleteHasNoChildren_thenChangeTree() {
val n = Node(1, Node(0))
n.delete(0)
assertEquals(1, n.key)
assertNull(n.left)
assertNull(n.right)
}
/**
* Test suit for removal
* 1. tree depth: 2
* 2. value to delete: present
* 3. # child nodes: 1
*/
@Test
fun givenTreeDepthTwo_whenNodeToDeleteHasOneChild_thenChangeTree() {
val n = Node(2, Node(0, null, Node(1)), Node(3))
n.delete(0)
assertEquals(2, n.key)
with(n.right!!) {
assertEquals(3, key)
assertNull(left)
assertNull(right)
}
with(n.left!!) {
assertEquals(1, key)
assertNull(left)
assertNull(right)
}
}
@Test
fun givenTreeDepthThree_whenNodeToDeleteHasTwoChildren_thenChangeTree() {
val l = Node(2, Node(1), Node(5, Node(4), Node(6)))
val r = Node(10, Node(9), Node(11))
val n = Node(8, l, r)
n.delete(8)
assertEquals(6, n.key)
with(n.left!!) {
assertEquals(2, key)
assertEquals(1, left!!.key)
assertEquals(5, right!!.key)
assertEquals(4, right!!.left!!.key)
}
with(n.right!!) {
assertEquals(10, key)
assertEquals(9, left!!.key)
assertEquals(11, right!!.key)
}
}
}

View File

@@ -1,140 +0,0 @@
package com.baeldung.builder
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
internal class BuilderPatternUnitTest {
@Test
fun whenBuildingFoodOrderSettingValues_thenFieldsNotNull() {
val foodOrder = FoodOrder.Builder()
.bread("white bread")
.meat("bacon")
.fish("salmon")
.condiments("olive oil")
.build()
Assertions.assertNotNull(foodOrder.bread)
Assertions.assertNotNull(foodOrder.meat)
Assertions.assertNotNull(foodOrder.condiments)
Assertions.assertNotNull(foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderSettingValues_thenFieldsContainsValues() {
val foodOrder = FoodOrder.Builder()
.bread("white bread")
.meat("bacon")
.fish("salmon")
.condiments("olive oil")
.build()
Assertions.assertEquals("white bread", foodOrder.bread)
Assertions.assertEquals("bacon", foodOrder.meat)
Assertions.assertEquals("olive oil", foodOrder.condiments)
Assertions.assertEquals("salmon", foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderWithoutSettingValues_thenFieldsNull() {
val foodOrder = FoodOrder.Builder()
.build()
Assertions.assertNull(foodOrder.bread)
Assertions.assertNull(foodOrder.meat)
Assertions.assertNull(foodOrder.condiments)
Assertions.assertNull(foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderNamedSettingValues_thenFieldsNotNull() {
val foodOrder = FoodOrderNamed(
meat = "bacon",
fish = "salmon",
condiments = "olive oil",
bread = "white bread"
)
Assertions.assertNotNull(foodOrder.bread)
Assertions.assertNotNull(foodOrder.meat)
Assertions.assertNotNull(foodOrder.condiments)
Assertions.assertNotNull(foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderNamedSettingValues_thenFieldsContainsValues() {
val foodOrder = FoodOrderNamed(
meat = "bacon",
fish = "salmon",
condiments = "olive oil",
bread = "white bread"
)
Assertions.assertEquals("white bread", foodOrder.bread)
Assertions.assertEquals("bacon", foodOrder.meat)
Assertions.assertEquals("olive oil", foodOrder.condiments)
Assertions.assertEquals("salmon", foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderNamedWithoutSettingValues_thenFieldsNull() {
val foodOrder = FoodOrderNamed()
Assertions.assertNull(foodOrder.bread)
Assertions.assertNull(foodOrder.meat)
Assertions.assertNull(foodOrder.condiments)
Assertions.assertNull(foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderApplySettingValues_thenFieldsNotNull() {
val foodOrder = FoodOrderApply().apply {
meat = "bacon"
fish = "salmon"
condiments = "olive oil"
bread = "white bread"
}
Assertions.assertNotNull(foodOrder.bread)
Assertions.assertNotNull(foodOrder.meat)
Assertions.assertNotNull(foodOrder.condiments)
Assertions.assertNotNull(foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderApplySettingValues_thenFieldsContainsValues() {
val foodOrder = FoodOrderApply().apply {
meat = "bacon"
fish = "salmon"
condiments = "olive oil"
bread = "white bread"
}
Assertions.assertEquals("white bread", foodOrder.bread)
Assertions.assertEquals("bacon", foodOrder.meat)
Assertions.assertEquals("olive oil", foodOrder.condiments)
Assertions.assertEquals("salmon", foodOrder.fish)
}
@Test
fun whenBuildingFoodOrderApplyWithoutSettingValues_thenFieldsNull() {
val foodOrder = FoodOrderApply()
Assertions.assertNull(foodOrder.bread)
Assertions.assertNull(foodOrder.meat)
Assertions.assertNull(foodOrder.condiments)
Assertions.assertNull(foodOrder.fish)
}
}

View File

@@ -1,30 +0,0 @@
package com.baeldung.gson
import com.google.gson.Gson
import org.junit.Assert
import org.junit.Test
class GsonUnitTest {
var gson = Gson()
@Test
fun givenObject_thenGetJSONString() {
var jsonString = gson.toJson(TestModel(1, "Test"))
Assert.assertEquals(jsonString, "{\"id\":1,\"description\":\"Test\"}")
}
@Test
fun givenJSONString_thenGetObject() {
var jsonString = "{\"id\":1,\"description\":\"Test\"}";
var testModel = gson.fromJson(jsonString, TestModel::class.java)
Assert.assertEquals(testModel.id, 1)
Assert.assertEquals(testModel.description, "Test")
}
data class TestModel(
val id: Int,
val description: String
)
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.junit5
class Calculator {
fun add(a: Int, b: Int) = a + b
fun divide(a: Int, b: Int) = if (b == 0) {
throw DivideByZeroException(a)
} else {
a / b
}
fun square(a: Int) = a * a
fun squareRoot(a: Int) = Math.sqrt(a.toDouble())
fun log(base: Int, value: Int) = Math.log(value.toDouble()) / Math.log(base.toDouble())
}

View File

@@ -1,82 +0,0 @@
package com.baeldung.junit5
import org.junit.jupiter.api.*
import org.junit.jupiter.api.function.Executable
class CalculatorUnitTest {
private val calculator = Calculator()
@Test
fun `Adding 1 and 3 should be equal to 4`() {
Assertions.assertEquals(4, calculator.add(1, 3))
}
@Test
fun `Dividing by zero should throw the DivideByZeroException`() {
val exception = Assertions.assertThrows(DivideByZeroException::class.java) {
calculator.divide(5, 0)
}
Assertions.assertEquals(5, exception.numerator)
}
@Test
fun `The square of a number should be equal to that number multiplied in itself`() {
Assertions.assertAll(
Executable { Assertions.assertEquals(1, calculator.square(1)) },
Executable { Assertions.assertEquals(4, calculator.square(2)) },
Executable { Assertions.assertEquals(9, calculator.square(3)) }
)
}
@TestFactory
fun testSquaresFactory() = listOf(
DynamicTest.dynamicTest("when I calculate 1^2 then I get 1") { Assertions.assertEquals(1,calculator.square(1))},
DynamicTest.dynamicTest("when I calculate 2^2 then I get 4") { Assertions.assertEquals(4,calculator.square(2))},
DynamicTest.dynamicTest("when I calculate 3^2 then I get 9") { Assertions.assertEquals(9,calculator.square(3))}
)
@TestFactory
fun testSquaresFactory2() = listOf(
1 to 1,
2 to 4,
3 to 9,
4 to 16,
5 to 25)
.map { (input, expected) ->
DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") {
Assertions.assertEquals(expected, calculator.square(input))
}
}
private val squaresTestData = listOf(
1 to 1,
2 to 4,
3 to 9,
4 to 16,
5 to 25)
@TestFactory
fun testSquaresFactory3() = squaresTestData
.map { (input, expected) ->
DynamicTest.dynamicTest("when I calculate $input^2 then I get $expected") {
Assertions.assertEquals(expected, calculator.square(input))
}
}
@TestFactory
fun testSquareRootsFactory3() = squaresTestData
.map { (expected, input) ->
DynamicTest.dynamicTest("I calculate the square root of $input then I get $expected") {
Assertions.assertEquals(expected.toDouble(), calculator.squareRoot(input))
}
}
@Tags(
Tag("slow"),
Tag("logarithms")
)
@Test
fun `Log to base 2 of 8 should be equal to 3`() {
Assertions.assertEquals(3.0, calculator.log(2, 8))
}
}

View File

@@ -1,3 +0,0 @@
package com.baeldung.junit5
class DivideByZeroException(val numerator: Int) : Exception()

View File

@@ -1,22 +0,0 @@
package com.baeldung.junit5
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
class SimpleUnitTest {
@Test
fun `isEmpty should return true for empty lists`() {
val list = listOf<String>()
Assertions.assertTrue(list::isEmpty)
}
@Test
@Disabled
fun `3 is equal to 4`() {
Assertions.assertEquals(3, 4) {
"Three does not equal four"
}
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.nullassertion
import org.junit.Test
import kotlin.test.assertEquals
class NotNullAssertionUnitTest {
@Test
fun givenNullableValue_WhenNotNull_ShouldExtractTheValue() {
val answer: String? = "42"
assertEquals(42, answer!!.toInt())
}
@Test(expected = KotlinNullPointerException::class)
fun givenNullableValue_WhenIsNull_ThenShouldThrow() {
val noAnswer: String? = null
noAnswer!!
}
}

View File

@@ -1,143 +0,0 @@
package com.baeldung.scope
import org.junit.Test
import kotlin.test.assertTrue
class ScopeFunctionsUnitTest {
class Logger {
var called : Boolean = false
fun info(message: String) {
called = true
}
fun wasCalled() = called
}
@Test
fun shouldTransformWhenLetFunctionUsed() {
val stringBuider = StringBuilder()
val numberOfCharacters = stringBuider.let {
it.append("This is a transformation function.")
it.append("It takes a StringBuilder instance and returns the number of characters in the generated String")
it.length
}
assertTrue {
numberOfCharacters == 128
}
}
@Test
fun shouldHandleNullabilityWhenLetFunctionUsed() {
val message: String? = "hello there!"
val charactersInMessage = message?.let {
"At this point is safe to reference the variable. Let's print the message: $it"
} ?: "default value"
assertTrue {
charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!")
}
val aNullMessage = null
val thisIsNull = aNullMessage?.let {
"At this point it would be safe to reference the variable. But it will not really happen because it is null. Let's reference: $it"
} ?: "default value"
assertTrue {
thisIsNull.equals("default value")
}
}
@Test
fun shouldInitializeObjectWhenUsingApply() {
val aStudent = Student().apply {
studentId = "1234567"
name = "Mary"
surname = "Smith"
}
assertTrue {
aStudent.name.equals("Mary")
}
}
@Test
fun shouldAllowBuilderStyleObjectDesignWhenApplyUsedInClassMethods() {
val teacher = Teacher()
.setId(1000)
.setName("Martha")
.setSurname("Spector")
assertTrue {
teacher.surname.equals("Spector")
}
}
@Test
fun shouldAllowSideEffectWhenUsingAlso() {
val restClient = RestClient("http://www.someurl.com")
val logger = Logger()
val headers = restClient
.getResponse()
.also { logger.info(it.toString()) }
.headers
assertTrue {
logger.wasCalled() && headers.headerInfo.equals("some header info")
}
}
@Test
fun shouldInitializeFieldWhenAlsoUsed() {
val aStudent = Student().also { it.name = "John"}
assertTrue {
aStudent.name.equals("John")
}
}
@Test
fun shouldLogicallyGroupObjectCallsWhenUsingWith() {
val bankAccount = BankAccount(1000)
with (bankAccount) {
checkAuthorization("someone")
addPayee("some payee")
makePayment("payment information")
}
}
@Test
fun shouldConvertObjectWhenRunUsed() {
val stringBuider = StringBuilder()
val numberOfCharacters = stringBuider.run {
append("This is a transformation function.")
append("It takes a StringBuilder instance and returns the number of characters in the generated String")
length
}
assertTrue {
numberOfCharacters == 128
}
}
@Test
fun shouldHandleNullabilityWhenRunIsUsed() {
val message: String? = "hello there!"
val charactersInMessage = message?.run {
"At this point is safe to reference the variable. Let's print the message: $this"
} ?: "default value"
assertTrue {
charactersInMessage.equals("At this point is safe to reference the variable. Let's print the message: hello there!")
}
}
}

View File

@@ -0,0 +1,54 @@
package com.baeldung.sequeces
import org.junit.Test
import kotlin.test.assertEquals
import java.time.Instant
class SequencesTest {
@Test
fun shouldBuildSequenceWhenUsingFromElements() {
val seqOfElements = sequenceOf("first" ,"second", "third")
.toList()
assertEquals(3, seqOfElements.count())
}
@Test
fun shouldBuildSequenceWhenUsingFromFunction() {
val seqFromFunction = generateSequence(Instant.now()) {it.plusSeconds(1)}
.take(3)
.toList()
assertEquals(3, seqFromFunction.count())
}
@Test
fun shouldBuildSequenceWhenUsingFromChunks() {
val seqFromChunks = sequence {
yield(1)
yieldAll((2..5).toList())
}.toList()
assertEquals(5, seqFromChunks.count())
}
@Test
fun shouldBuildSequenceWhenUsingFromCollection() {
val seqFromIterable = (1..10)
.asSequence()
.toList()
assertEquals(10, seqFromIterable.count())
}
@Test
fun shouldShowNoCountDiffWhenUsingWithAndWithoutSequence() {
val withSequence = (1..10).asSequence()
.filter{it % 2 == 1}
.map { it * 2 }
.toList()
val withoutSequence = (1..10)
.filter{it % 2 == 1}
.map { it * 2 }
.toList()
assertEquals(withSequence.count(), withoutSequence.count())
}
}

View File

@@ -1,13 +0,0 @@
package com.baeldung.sorting
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class SortingExampleKtTest {
@Test
fun naturalOrderComparator_ShouldBeAscendingTest() {
val resultingList = listOf(1, 5, 6, 6, 2, 3, 4).sortedWith(getSimpleComparator())
assertTrue(listOf(1, 2, 3, 4, 5, 6, 6) == resultingList)
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.ternary
import org.junit.Test
import kotlin.test.assertEquals
class TernaryOperatorTest {
@Test
fun `using If`() {
val a = true
val result = if (a) "yes" else "no"
assertEquals("yes", result)
}
@Test
fun `using When`() {
val a = true
val result = when(a) {
true -> "yes"
false -> "no"
}
assertEquals("yes", result)
}
@Test
fun `using elvis`() {
val a: String? = null
val result = a ?: "Default"
assertEquals("Default", result)
}
}