[BAEL-19886] - moved related articles to the new core-kotlin-modules/core-kotlin module
This commit is contained in:
15
core-kotlin-modules/core-kotlin/README.md
Normal file
15
core-kotlin-modules/core-kotlin/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
## Core Kotlin
|
||||
|
||||
This module contains articles about Kotlin core features.
|
||||
|
||||
### Relevant articles:
|
||||
- [Introduction to the Kotlin Language](https://www.baeldung.com/kotlin)
|
||||
- [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)
|
||||
29
core-kotlin-modules/core-kotlin/pom.xml
Normal file
29
core-kotlin-modules/core-kotlin/pom.xml
Normal file
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-kotlin</artifactId>
|
||||
<name>core-kotlin</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung.core-kotlin-modules</groupId>
|
||||
<artifactId>core-kotlin-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit.platform.version>1.1.1</junit.platform.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.interoperability;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
|
||||
public class ArrayExample {
|
||||
|
||||
public int sumValues(int[] nums) {
|
||||
int res = 0;
|
||||
|
||||
for (int x:nums) {
|
||||
res += x;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
public void writeList() throws IOException {
|
||||
File file = new File("E://file.txt");
|
||||
FileReader fr = new FileReader(file);
|
||||
fr.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.interoperability;
|
||||
|
||||
public class Customer {
|
||||
|
||||
private String firstName;
|
||||
private String lastName;
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.introduction;
|
||||
|
||||
public class StringUtils {
|
||||
public static String toUpperCase(String name) {
|
||||
return name.toUpperCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.mavenjavakotlin;
|
||||
|
||||
import com.baeldung.mavenjavakotlin.services.JavaService;
|
||||
|
||||
public class Application {
|
||||
|
||||
private static final String JAVA = "java";
|
||||
private static final String KOTLIN = "kotlin";
|
||||
|
||||
public static void main(String[] args) {
|
||||
String language = args[0];
|
||||
switch (language) {
|
||||
case JAVA:
|
||||
new JavaService().sayHello();
|
||||
break;
|
||||
case KOTLIN:
|
||||
new KotlinService().sayHello();
|
||||
break;
|
||||
default:
|
||||
// Do nothing
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.mavenjavakotlin.services;
|
||||
|
||||
public class JavaService {
|
||||
|
||||
public void sayHello() {
|
||||
System.out.println("Java says 'Hello World!'");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
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() })
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.builder
|
||||
|
||||
class FoodOrderApply {
|
||||
var bread: String? = null
|
||||
var condiments: String? = null
|
||||
var meat: String? = null
|
||||
var fish: String? = null
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.builder
|
||||
|
||||
data class FoodOrderNamed(
|
||||
val bread: String? = null,
|
||||
val condiments: String? = null,
|
||||
val meat: String? = null,
|
||||
val fish: String? = null)
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.builder
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
FoodOrder.Builder()
|
||||
.bread("bread")
|
||||
.condiments("condiments")
|
||||
.meat("meat")
|
||||
.fish("bread").let { println(it) }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.introduction
|
||||
|
||||
fun main(args: Array<String>){
|
||||
println("hello word")
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.introduction
|
||||
|
||||
open class Item(val id: String, val name: String = "unknown_name") {
|
||||
open fun getIdOfItem(): String {
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
class ItemWithCategory(id: String, name: String, val categoryId: String) : Item(id, name) {
|
||||
override fun getIdOfItem(): String {
|
||||
return id + name
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.baeldung.introduction
|
||||
|
||||
import java.util.*
|
||||
|
||||
class ItemService {
|
||||
fun findItemNameForId(id: String): Item? {
|
||||
val itemId = UUID.randomUUID().toString()
|
||||
return Item(itemId, "name-$itemId")
|
||||
}
|
||||
}
|
||||
|
||||
class ItemManager(val categoryId: String, val dbConnection: String) {
|
||||
var email = ""
|
||||
|
||||
constructor(categoryId: String, dbConnection: String, email: String)
|
||||
: this(categoryId, dbConnection) {
|
||||
this.email = email
|
||||
}
|
||||
|
||||
fun isFromSpecificCategory(catId: String): Boolean {
|
||||
return categoryId == catId
|
||||
}
|
||||
|
||||
fun makeAnalyisOfCategory(catId: String): Unit {
|
||||
val result = if (catId == "100") "Yes" else "No"
|
||||
println(result)
|
||||
`object`()
|
||||
}
|
||||
|
||||
fun sum(a: Int, b: Int): Int {
|
||||
return a + b
|
||||
}
|
||||
|
||||
fun `object`(): String {
|
||||
return "this is object"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val numbers = arrayOf("first", "second", "third", "fourth")
|
||||
|
||||
for (n in numbers) {
|
||||
println(n)
|
||||
}
|
||||
|
||||
for (i in 2..9 step 2) {
|
||||
println(i)
|
||||
}
|
||||
|
||||
val res = 1.rangeTo(10).map { it * 2 }
|
||||
println(res)
|
||||
|
||||
val firstName = "Tom"
|
||||
val secondName = "Mary"
|
||||
val concatOfNames = "$firstName + $secondName"
|
||||
println("Names: $concatOfNames")
|
||||
val sum = "four: ${2 + 2}"
|
||||
|
||||
val itemManager = ItemManager("cat_id", "db://connection")
|
||||
ItemManager(categoryId = "catId", dbConnection = "db://Connection")
|
||||
val result = "function result: ${itemManager.isFromSpecificCategory("1")}"
|
||||
println(result)
|
||||
|
||||
val number = 2
|
||||
if (number < 10) {
|
||||
println("number less that 10")
|
||||
} else if (number > 10) {
|
||||
println("number is greater that 10")
|
||||
}
|
||||
|
||||
val name = "John"
|
||||
when (name) {
|
||||
"John" -> println("Hi man")
|
||||
"Alice" -> println("Hi lady")
|
||||
}
|
||||
|
||||
val items = listOf(1, 2, 3, 4)
|
||||
|
||||
|
||||
val rwList = mutableListOf(1, 2, 3)
|
||||
rwList.add(5)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.baeldung.kotlin
|
||||
package com.baeldung.introduction
|
||||
|
||||
import java.util.concurrent.ThreadLocalRandom
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.introduction
|
||||
|
||||
class MathematicsOperations {
|
||||
fun addTwoNumbers(a: Int, b: Int): Int {
|
||||
return a + b
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.mavenjavakotlin
|
||||
|
||||
class KotlinService {
|
||||
|
||||
fun sayHello() {
|
||||
System.out.println("Kotlin says 'Hello World!'")
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
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
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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))
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.introduction;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class JavaCallToKotlinUnitTest {
|
||||
@Test
|
||||
public void givenKotlinClass_whenCallFromJava_shouldProduceResults() {
|
||||
//when
|
||||
int res = new MathematicsOperations().addTwoNumbers(2, 4);
|
||||
|
||||
//then
|
||||
assertEquals(6, res);
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
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)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.interoperability
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class ArrayTest {
|
||||
|
||||
@Test
|
||||
fun givenArray_whenValidateArrayType_thenComplete () {
|
||||
val ex = com.baeldung.interoperability.ArrayExample()
|
||||
val numArray = intArrayOf(1, 2, 3)
|
||||
|
||||
assertEquals(ex.sumValues(numArray), 6)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenCustomer_whenGetSuperType_thenComplete() {
|
||||
val instance = com.baeldung.interoperability.Customer::class
|
||||
val supertypes = instance.supertypes
|
||||
|
||||
assertEquals(supertypes[0].toString(), "kotlin.Any")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenCustomer_whenGetConstructor_thenComplete() {
|
||||
val instance = com.baeldung.interoperability.Customer::class.java
|
||||
val constructors = instance.constructors
|
||||
|
||||
assertEquals(constructors.size, 1)
|
||||
assertEquals(constructors[0].name, "com.baeldung.interoperability.Customer")
|
||||
}
|
||||
|
||||
fun makeReadFile() {
|
||||
val ax = com.baeldung.interoperability.ArrayExample()
|
||||
ax.writeList()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.interoperability
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
class CustomerTest {
|
||||
|
||||
@Test
|
||||
fun givenCustomer_whenNameAndLastNameAreAssigned_thenComplete() {
|
||||
val customer = com.baeldung.interoperability.Customer()
|
||||
|
||||
// Setter method is being called
|
||||
customer.firstName = "Frodo"
|
||||
customer.lastName = "Baggins"
|
||||
|
||||
// Getter method is being called
|
||||
assertEquals(customer.firstName, "Frodo")
|
||||
assertEquals(customer.lastName, "Baggins")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.introduction
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertNotNull
|
||||
|
||||
class ItemServiceTest {
|
||||
|
||||
@Test
|
||||
fun givenItemId_whenGetForOptionalItem_shouldMakeActionOnNonNullValue() {
|
||||
//given
|
||||
val id = "item_id"
|
||||
val itemService = ItemService()
|
||||
|
||||
//when
|
||||
val result = itemService.findItemNameForId(id)
|
||||
|
||||
//then
|
||||
assertNotNull(result?.let { it -> it.id })
|
||||
assertNotNull(result!!.id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.introduction
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
|
||||
class KotlinJavaInteroperabilityTest {
|
||||
|
||||
@Test
|
||||
fun givenLowercaseString_whenExecuteMethodFromJavaStringUtils_shouldReturnStringUppercase() {
|
||||
//given
|
||||
val name = "tom"
|
||||
|
||||
//whene
|
||||
val res = StringUtils.toUpperCase(name)
|
||||
|
||||
//then
|
||||
assertEquals(res, "TOM")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.introduction
|
||||
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertEquals
|
||||
|
||||
|
||||
class LambdaTest {
|
||||
|
||||
@Test
|
||||
fun givenListOfNumber_whenDoingOperationsUsingLambda_shouldReturnProperResult() {
|
||||
//given
|
||||
val listOfNumbers = listOf(1, 2, 3)
|
||||
|
||||
//when
|
||||
val sum = listOfNumbers.reduce { a, b -> a + b }
|
||||
|
||||
//then
|
||||
assertEquals(6, sum)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
package com.baeldung.kotlin
|
||||
package com.baeldung.introduction
|
||||
|
||||
import com.baeldung.kotlin.ListExtension
|
||||
import org.junit.Test
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class ListExtensionTest {
|
||||
|
||||
@Test
|
||||
fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList(){
|
||||
fun givenList_whenExecuteExtensionFunctionOnList_shouldReturnRandomElementOfList() {
|
||||
//given
|
||||
val elements = listOf("a", "b", "c")
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
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())
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.junit5
|
||||
|
||||
class DivideByZeroException(val numerator: Int) : Exception()
|
||||
@@ -0,0 +1,22 @@
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.util.concurrent.ThreadLocalRandom
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
class RandomNumberTest {
|
||||
|
||||
@Test
|
||||
fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() {
|
||||
val randomNumber = Math.random()
|
||||
assertTrue { randomNumber >=0 }
|
||||
assertTrue { randomNumber <= 1 }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInDefaultRanges() {
|
||||
val randomDouble = ThreadLocalRandom.current().nextDouble()
|
||||
val randomInteger = ThreadLocalRandom.current().nextInt()
|
||||
val randomLong = ThreadLocalRandom.current().nextLong()
|
||||
assertTrue { randomDouble >= 0 }
|
||||
assertTrue { randomDouble <= 1 }
|
||||
assertTrue { randomInteger >= Integer.MIN_VALUE }
|
||||
assertTrue { randomInteger <= Integer.MAX_VALUE }
|
||||
assertTrue { randomLong >= Long.MIN_VALUE }
|
||||
assertTrue { randomLong <= Long.MAX_VALUE }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenRandomNumberWithKotlinJSMath_thenResultIsBetween0And1() {
|
||||
val randomDouble = Math.random()
|
||||
assertTrue { randomDouble >=0 }
|
||||
assertTrue { randomDouble <= 1 }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenRandomNumberWithKotlinNumberRange_thenResultInGivenRange() {
|
||||
val randomInteger = (1..12).shuffled().first()
|
||||
assertTrue { randomInteger >= 1 }
|
||||
assertTrue { randomInteger <= 12 }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenRandomNumberWithJavaThreadLocalRandom_thenResultsInGivenRanges() {
|
||||
val randomDouble = ThreadLocalRandom.current().nextDouble(1.0, 10.0)
|
||||
val randomInteger = ThreadLocalRandom.current().nextInt(1, 10)
|
||||
val randomLong = ThreadLocalRandom.current().nextLong(1, 10)
|
||||
assertTrue { randomDouble >= 1 }
|
||||
assertTrue { randomDouble <= 10 }
|
||||
assertTrue { randomInteger >= 1 }
|
||||
assertTrue { randomInteger <= 10 }
|
||||
assertTrue { randomLong >= 1 }
|
||||
assertTrue { randomLong <= 10 }
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
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!")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>core-kotlin</module>
|
||||
<module>core-kotlin-advanced</module>
|
||||
<module>core-kotlin-annotations</module>
|
||||
<module>core-kotlin-collections</module>
|
||||
|
||||
Reference in New Issue
Block a user