[BAEL-8472] - Resolved conflict
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.klaxon
|
||||
|
||||
import com.beust.klaxon.Json
|
||||
|
||||
class CustomProduct(
|
||||
@Json(name = "productName")
|
||||
val name: String,
|
||||
@Json(ignored = true)
|
||||
val id: Int)
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.klaxon
|
||||
|
||||
class Product(val name: String)
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.klaxon
|
||||
|
||||
data class ProductData(val name: String, val capacityInGb: Int)
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.kotlin.kodein
|
||||
|
||||
class Controller(private val service : Service)
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.kotlin.kodein
|
||||
|
||||
interface Dao
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.kotlin.kodein
|
||||
|
||||
class JdbcDao : Dao
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.kotlin.kodein
|
||||
|
||||
class MongoDao : Dao
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung.kotlin.kodein
|
||||
|
||||
class Service(private val dao: Dao, private val tag: String)
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
interface BookService {
|
||||
fun inStock(bookId: Int): Boolean
|
||||
fun lend(bookId: Int, memberId: Int)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.kotlin
|
||||
|
||||
class LendBookManager(val bookService:BookService) {
|
||||
fun checkout(bookId: Int, memberId: Int) {
|
||||
if(bookService.inStock(bookId)) {
|
||||
bookService.lend(bookId, memberId)
|
||||
} else {
|
||||
throw IllegalStateException("Book is not available")
|
||||
}
|
||||
}
|
||||
}
|
||||
73
kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt
Executable file
73
kotlin-libraries/src/main/kotlin/com/baeldung/ktor/APIServer.kt
Executable file
@@ -0,0 +1,73 @@
|
||||
@file:JvmName("APIServer")
|
||||
|
||||
|
||||
import io.ktor.application.call
|
||||
import io.ktor.application.install
|
||||
import io.ktor.features.CallLogging
|
||||
import io.ktor.features.ContentNegotiation
|
||||
import io.ktor.features.DefaultHeaders
|
||||
import io.ktor.gson.gson
|
||||
import io.ktor.request.path
|
||||
import io.ktor.request.receive
|
||||
import io.ktor.response.respond
|
||||
import io.ktor.routing.*
|
||||
import io.ktor.server.engine.embeddedServer
|
||||
import io.ktor.server.netty.Netty
|
||||
import org.slf4j.event.Level
|
||||
|
||||
data class Author(val name: String, val website: String)
|
||||
data class ToDo(var id: Int, val name: String, val description: String, val completed: Boolean)
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
|
||||
val toDoList = ArrayList<ToDo>();
|
||||
val jsonResponse = """{
|
||||
"id": 1,
|
||||
"task": "Pay waterbill",
|
||||
"description": "Pay water bill today",
|
||||
}"""
|
||||
|
||||
|
||||
embeddedServer(Netty, 8080) {
|
||||
install(DefaultHeaders) {
|
||||
header("X-Developer", "Baeldung")
|
||||
}
|
||||
install(CallLogging) {
|
||||
level = Level.DEBUG
|
||||
filter { call -> call.request.path().startsWith("/todo") }
|
||||
filter { call -> call.request.path().startsWith("/author") }
|
||||
}
|
||||
install(ContentNegotiation) {
|
||||
gson {
|
||||
setPrettyPrinting()
|
||||
}
|
||||
}
|
||||
routing() {
|
||||
route("/todo") {
|
||||
post {
|
||||
var toDo = call.receive<ToDo>();
|
||||
toDo.id = toDoList.size;
|
||||
toDoList.add(toDo);
|
||||
call.respond("Added")
|
||||
|
||||
}
|
||||
delete("/{id}") {
|
||||
call.respond(toDoList.removeAt(call.parameters["id"]!!.toInt()));
|
||||
}
|
||||
get("/{id}") {
|
||||
|
||||
call.respond(toDoList[call.parameters["id"]!!.toInt()]);
|
||||
}
|
||||
get {
|
||||
call.respond(toDoList);
|
||||
}
|
||||
}
|
||||
get("/author"){
|
||||
call.respond(Author("Baeldung","baeldung.com"));
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}.start(wait = true)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package com.baeldung.klaxon
|
||||
|
||||
import com.beust.klaxon.JsonArray
|
||||
import com.beust.klaxon.JsonObject
|
||||
import com.beust.klaxon.JsonReader
|
||||
import com.beust.klaxon.Klaxon
|
||||
import com.beust.klaxon.Parser
|
||||
import com.beust.klaxon.PathMatcher
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.assertj.core.api.SoftAssertions.assertSoftly
|
||||
import org.junit.Assert
|
||||
import org.junit.jupiter.api.Test
|
||||
import java.io.StringReader
|
||||
import java.util.regex.Pattern
|
||||
|
||||
class KlaxonUnitTest {
|
||||
|
||||
@Test
|
||||
fun giveProduct_whenSerialize_thenGetJsonString() {
|
||||
val product = Product("HDD")
|
||||
val result = Klaxon().toJsonString(product)
|
||||
|
||||
assertThat(result).isEqualTo("""{"name" : "HDD"}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun giveJsonString_whenDeserialize_thenGetProduct() {
|
||||
val result = Klaxon().parse<Product>("""
|
||||
{
|
||||
"name" : "RAM"
|
||||
}
|
||||
""")
|
||||
|
||||
assertThat(result?.name).isEqualTo("RAM")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun giveCustomProduct_whenSerialize_thenGetJsonString() {
|
||||
val product = CustomProduct("HDD", 1)
|
||||
val result = Klaxon().toJsonString(product)
|
||||
|
||||
assertThat(result).isEqualTo("""{"productName" : "HDD"}""")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun giveJsonArray_whenStreaming_thenGetProductArray() {
|
||||
val jsonArray = """
|
||||
[
|
||||
{ "name" : "HDD", "capacityInGb" : 512 },
|
||||
{ "name" : "RAM", "capacityInGb" : 16 }
|
||||
]"""
|
||||
val expectedArray = arrayListOf(ProductData("HDD", 512),
|
||||
ProductData("RAM", 16))
|
||||
val klaxon = Klaxon()
|
||||
val productArray = arrayListOf<ProductData>()
|
||||
JsonReader(StringReader(jsonArray)).use { reader ->
|
||||
reader.beginArray {
|
||||
while (reader.hasNext()) {
|
||||
val product = klaxon.parse<ProductData>(reader)
|
||||
productArray.add(product!!)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(productArray).hasSize(2).isEqualTo(expectedArray)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun giveJsonString_whenParser_thenGetJsonObject() {
|
||||
val jsonString = StringBuilder("""
|
||||
{
|
||||
"name" : "HDD",
|
||||
"capacityInGb" : 512,
|
||||
"sizeInInch" : 2.5
|
||||
}
|
||||
""")
|
||||
val parser = Parser()
|
||||
val json = parser.parse(jsonString) as JsonObject
|
||||
|
||||
assertThat(json).hasSize(3).containsEntry("name", "HDD").containsEntry("capacityInGb", 512).containsEntry("sizeInInch", 2.5)
|
||||
}
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@Test
|
||||
fun giveJsonStringArray_whenParser_thenGetJsonArray() {
|
||||
val jsonString = StringBuilder("""
|
||||
[
|
||||
{ "name" : "SDD" },
|
||||
{ "madeIn" : "Taiwan" },
|
||||
{ "warrantyInYears" : 5 }
|
||||
]""")
|
||||
val parser = Parser()
|
||||
val json = parser.parse(jsonString) as JsonArray<JsonObject>
|
||||
|
||||
assertSoftly({ softly ->
|
||||
softly.assertThat(json).hasSize(3)
|
||||
softly.assertThat(json[0]["name"]).isEqualTo("SDD")
|
||||
softly.assertThat(json[1]["madeIn"]).isEqualTo("Taiwan")
|
||||
softly.assertThat(json[2]["warrantyInYears"]).isEqualTo(5)
|
||||
})
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenJsonString_whenStreaming_thenProcess() {
|
||||
val jsonString = """
|
||||
{
|
||||
"name" : "HDD",
|
||||
"madeIn" : "Taiwan",
|
||||
"warrantyInYears" : 5
|
||||
"hasStock" : true
|
||||
"capacitiesInTb" : [ 1, 2 ],
|
||||
"features" : { "cacheInMb" : 64, "speedInRpm" : 7200 }
|
||||
}"""
|
||||
|
||||
JsonReader(StringReader(jsonString)).use { reader ->
|
||||
reader.beginObject {
|
||||
while (reader.hasNext()) {
|
||||
val readName = reader.nextName()
|
||||
when (readName) {
|
||||
"name" -> assertThat(reader.nextString()).isEqualTo("HDD")
|
||||
"madeIn" -> assertThat(reader.nextString()).isEqualTo("Taiwan")
|
||||
"warrantyInYears" -> assertThat(reader.nextInt()).isEqualTo(5)
|
||||
"hasStock" -> assertThat(reader.nextBoolean()).isEqualTo(true)
|
||||
"capacitiesInTb" -> assertThat(reader.nextArray()).contains(1, 2)
|
||||
"features" -> assertThat(reader.nextObject()).containsEntry("cacheInMb", 64).containsEntry("speedInRpm", 7200)
|
||||
else -> Assert.fail("Unexpected name: $readName")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
fun givenDiskInventory_whenRegexMatches_thenGetTypes() {
|
||||
val jsonString = """
|
||||
{
|
||||
"inventory" : {
|
||||
"disks" : [
|
||||
{
|
||||
"type" : "HDD",
|
||||
"sizeInGb" : 1000
|
||||
},
|
||||
{
|
||||
"type" : "SDD",
|
||||
"sizeInGb" : 512
|
||||
}
|
||||
]
|
||||
}
|
||||
}"""
|
||||
val pathMatcher = object : PathMatcher {
|
||||
override fun pathMatches(path: String) = Pattern.matches(".*inventory.*disks.*type.*", path)
|
||||
|
||||
override fun onMatch(path: String, value: Any) {
|
||||
when (path) {
|
||||
"$.inventory.disks[0].type" -> assertThat(value).isEqualTo("HDD")
|
||||
"$.inventory.disks[1].type" -> assertThat(value).isEqualTo("SDD")
|
||||
}
|
||||
}
|
||||
}
|
||||
Klaxon().pathMatcher(pathMatcher).parseJsonObject(StringReader(jsonString))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.baeldung.kotlin.khttp
|
||||
|
||||
import khttp.structures.files.FileLike
|
||||
import org.json.JSONObject
|
||||
import org.junit.Test
|
||||
import java.beans.ExceptionListener
|
||||
import java.beans.XMLEncoder
|
||||
import java.io.*
|
||||
import java.lang.Exception
|
||||
import java.net.ConnectException
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
import kotlin.test.fail
|
||||
|
||||
class KhttpLiveTest {
|
||||
|
||||
@Test
|
||||
fun whenHttpGetRequestIsMade_thenArgsAreReturned() {
|
||||
val response = khttp.get(
|
||||
url = "http://httpbin.org/get",
|
||||
params = mapOf("p1" to "1", "p2" to "2"))
|
||||
val args = response.jsonObject.getJSONObject("args")
|
||||
|
||||
assertEquals("1", args["p1"])
|
||||
assertEquals("2", args["p2"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenAlternateHttpGetRequestIsMade_thenArgsAreReturned() {
|
||||
val response = khttp.request(
|
||||
method = "GET",
|
||||
url = "http://httpbin.org/get",
|
||||
params = mapOf("p1" to "1", "p2" to "2"))
|
||||
val args = response.jsonObject.getJSONObject("args")
|
||||
|
||||
assertEquals("1", args["p1"])
|
||||
assertEquals("2", args["p2"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenHeadersAreSet_thenHeadersAreSent() {
|
||||
val response = khttp.get(
|
||||
url = "http://httpbin.org/get",
|
||||
headers = mapOf("header1" to "1", "header2" to "2"))
|
||||
val headers = response.jsonObject.getJSONObject("headers")
|
||||
|
||||
assertEquals("1", headers["Header1"])
|
||||
assertEquals("2", headers["Header2"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenHttpPostRequestIsMadeWithJson_thenBodyIsReturned() {
|
||||
val response = khttp.post(
|
||||
url = "http://httpbin.org/post",
|
||||
params = mapOf("p1" to "1", "p2" to "2"),
|
||||
json = mapOf("pr1" to "1", "pr2" to "2"))
|
||||
|
||||
val args = response.jsonObject.getJSONObject("args")
|
||||
|
||||
assertEquals("1", args["p1"])
|
||||
assertEquals("2", args["p2"])
|
||||
|
||||
val json = response.jsonObject.getJSONObject("json")
|
||||
|
||||
assertEquals("1", json["pr1"])
|
||||
assertEquals("2", json["pr2"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenHttpPostRequestIsMadeWithMapData_thenBodyIsReturned() {
|
||||
val response = khttp.post(
|
||||
url = "http://httpbin.org/post",
|
||||
params = mapOf("p1" to "1", "p2" to "2"),
|
||||
data = mapOf("pr1" to "1", "pr2" to "2"))
|
||||
|
||||
val args = response.jsonObject.getJSONObject("args")
|
||||
|
||||
assertEquals("1", args["p1"])
|
||||
assertEquals("2", args["p2"])
|
||||
|
||||
val form = response.jsonObject.getJSONObject("form")
|
||||
|
||||
assertEquals("1", form["pr1"])
|
||||
assertEquals("2", form["pr2"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenHttpPostRequestIsMadeWithFiles_thenBodyIsReturned() {
|
||||
val response = khttp.post(
|
||||
url = "http://httpbin.org/post",
|
||||
params = mapOf("p1" to "1", "p2" to "2"),
|
||||
files = listOf(
|
||||
FileLike("file1", "content1"),
|
||||
FileLike("file2", javaClass.getResource("KhttpTest.class").openStream().readBytes())))
|
||||
|
||||
val args = response.jsonObject.getJSONObject("args")
|
||||
|
||||
assertEquals("1", args["p1"])
|
||||
assertEquals("2", args["p2"])
|
||||
|
||||
val files = response.jsonObject.getJSONObject("files")
|
||||
|
||||
assertEquals("content1", files["file1"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenHttpPostRequestIsMadeWithInputStream_thenBodyIsReturned() {
|
||||
val response = khttp.post(
|
||||
url = "http://httpbin.org/post",
|
||||
params = mapOf("p1" to "1", "p2" to "2"),
|
||||
data = ByteArrayInputStream("content!".toByteArray()))
|
||||
|
||||
val args = response.jsonObject.getJSONObject("args")
|
||||
|
||||
assertEquals("1", args["p1"])
|
||||
assertEquals("2", args["p2"])
|
||||
|
||||
assertEquals("content!", response.jsonObject["data"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenHttpPostStreamingRequestIsMade_thenBodyIsReturnedInChunks() {
|
||||
val response = khttp.post(
|
||||
url = "http://httpbin.org/post",
|
||||
stream = true,
|
||||
json = mapOf("pr1" to "1", "pr2" to "2"))
|
||||
|
||||
val baos = ByteArrayOutputStream()
|
||||
response.contentIterator(chunkSize = 10).forEach { arr : ByteArray -> baos.write(arr) }
|
||||
val json = JSONObject(String(baos.toByteArray())).getJSONObject("json")
|
||||
|
||||
assertEquals("1", json["pr1"])
|
||||
assertEquals("2", json["pr2"])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenHttpRequestFails_thenExceptionIsThrown() {
|
||||
try {
|
||||
khttp.get(url = "http://localhost/nothing/to/see/here")
|
||||
|
||||
fail("Should have thrown an exception")
|
||||
} catch (e : ConnectException) {
|
||||
//Ok
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenHttpNotFound_thenExceptionIsThrown() {
|
||||
val response = khttp.get(url = "http://httpbin.org/nothing/to/see/here")
|
||||
|
||||
assertEquals(404, response.statusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package com.baeldung.kotlin.kodein
|
||||
|
||||
import com.github.salomonbrys.kodein.*
|
||||
import org.assertj.core.api.Assertions.assertThat
|
||||
import org.junit.Test
|
||||
|
||||
class KodeinUnitTest {
|
||||
|
||||
class InMemoryDao : Dao
|
||||
|
||||
@Test
|
||||
fun whenSingletonBinding_thenSingleInstanceIsCreated() {
|
||||
var created = false
|
||||
val kodein = Kodein {
|
||||
bind<Dao>() with singleton {
|
||||
created = true
|
||||
MongoDao()
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(created).isFalse()
|
||||
|
||||
val dao1: Dao = kodein.instance()
|
||||
|
||||
assertThat(created).isTrue()
|
||||
|
||||
val dao2: Dao = kodein.instance()
|
||||
|
||||
assertThat(dao1).isSameAs(dao2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenFactoryBinding_thenNewInstanceIsCreated() {
|
||||
val kodein = Kodein {
|
||||
bind<Dao>() with singleton { MongoDao() }
|
||||
bind<Service>() with factory { tag: String -> Service(instance(), tag) }
|
||||
}
|
||||
val service1: Service = kodein.with("myTag").instance()
|
||||
val service2: Service = kodein.with("myTag").instance()
|
||||
|
||||
assertThat(service1).isNotSameAs(service2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenProviderBinding_thenNewInstanceIsCreated() {
|
||||
val kodein = Kodein {
|
||||
bind<Dao>() with provider { MongoDao() }
|
||||
}
|
||||
val dao1: Dao = kodein.instance()
|
||||
val dao2: Dao = kodein.instance()
|
||||
|
||||
assertThat(dao1).isNotSameAs(dao2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenTaggedBinding_thenMultipleInstancesOfSameTypeCanBeRegistered() {
|
||||
val kodein = Kodein {
|
||||
bind<Dao>("dao1") with singleton { MongoDao() }
|
||||
bind<Dao>("dao2") with singleton { MongoDao() }
|
||||
}
|
||||
val dao1: Dao = kodein.instance("dao1")
|
||||
val dao2: Dao = kodein.instance("dao2")
|
||||
|
||||
assertThat(dao1).isNotSameAs(dao2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenEagerSingletonBinding_thenCreationIsEager() {
|
||||
var created = false
|
||||
val kodein = Kodein {
|
||||
bind<Dao>() with eagerSingleton {
|
||||
created = true
|
||||
MongoDao()
|
||||
}
|
||||
}
|
||||
|
||||
assertThat(created).isTrue()
|
||||
val dao1: Dao = kodein.instance()
|
||||
val dao2: Dao = kodein.instance()
|
||||
|
||||
assertThat(dao1).isSameAs(dao2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenMultitonBinding_thenInstancesAreReused() {
|
||||
val kodein = Kodein {
|
||||
bind<Dao>() with singleton { MongoDao() }
|
||||
bind<Service>() with multiton { tag: String -> Service(instance(), tag) }
|
||||
}
|
||||
val service1: Service = kodein.with("myTag").instance()
|
||||
val service2: Service = kodein.with("myTag").instance()
|
||||
|
||||
assertThat(service1).isSameAs(service2)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenInstanceBinding_thenItIsReused() {
|
||||
val dao = MongoDao()
|
||||
val kodein = Kodein {
|
||||
bind<Dao>() with instance(dao)
|
||||
}
|
||||
val fromContainer: Dao = kodein.instance()
|
||||
|
||||
assertThat(dao).isSameAs(fromContainer)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenConstantBinding_thenItIsAvailable() {
|
||||
val kodein = Kodein {
|
||||
constant("magic") with 42
|
||||
}
|
||||
val fromContainer: Int = kodein.instance("magic")
|
||||
|
||||
assertThat(fromContainer).isEqualTo(42)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenUsingModules_thenTransitiveDependenciesAreSuccessfullyResolved() {
|
||||
val jdbcModule = Kodein.Module {
|
||||
bind<Dao>() with singleton { JdbcDao() }
|
||||
}
|
||||
val kodein = Kodein {
|
||||
import(jdbcModule)
|
||||
bind<Controller>() with singleton { Controller(instance()) }
|
||||
bind<Service>() with singleton { Service(instance(), "myService") }
|
||||
}
|
||||
|
||||
val dao: Dao = kodein.instance()
|
||||
assertThat(dao).isInstanceOf(JdbcDao::class.java)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenComposition_thenBeansAreReUsed() {
|
||||
val persistenceContainer = Kodein {
|
||||
bind<Dao>() with singleton { MongoDao() }
|
||||
}
|
||||
val serviceContainer = Kodein {
|
||||
extend(persistenceContainer)
|
||||
bind<Service>() with singleton { Service(instance(), "myService") }
|
||||
}
|
||||
val fromPersistence: Dao = persistenceContainer.instance()
|
||||
val fromService: Dao = serviceContainer.instance()
|
||||
|
||||
assertThat(fromPersistence).isSameAs(fromService)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenOverriding_thenRightBeanIsUsed() {
|
||||
val commonModule = Kodein.Module {
|
||||
bind<Dao>() with singleton { MongoDao() }
|
||||
bind<Service>() with singleton { Service(instance(), "myService") }
|
||||
}
|
||||
val testContainer = Kodein {
|
||||
import(commonModule)
|
||||
bind<Dao>(overrides = true) with singleton { InMemoryDao() }
|
||||
}
|
||||
val dao: Dao = testContainer.instance()
|
||||
|
||||
assertThat(dao).isInstanceOf(InMemoryDao::class.java)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenMultiBinding_thenWorks() {
|
||||
val kodein = Kodein {
|
||||
bind() from setBinding<Dao>()
|
||||
bind<Dao>().inSet() with singleton { MongoDao() }
|
||||
bind<Dao>().inSet() with singleton { JdbcDao() }
|
||||
}
|
||||
val daos: Set<Dao> = kodein.instance()
|
||||
|
||||
assertThat(daos.map { it.javaClass as Class<*> }).containsOnly(MongoDao::class.java, JdbcDao::class.java)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenInjector_thenWorks() {
|
||||
class Controller2 {
|
||||
private val injector = KodeinInjector()
|
||||
val service: Service by injector.instance()
|
||||
fun injectDependencies(kodein: Kodein) = injector.inject(kodein)
|
||||
}
|
||||
|
||||
val kodein = Kodein {
|
||||
bind<Dao>() with singleton { MongoDao() }
|
||||
bind<Service>() with singleton { Service(instance(), "myService") }
|
||||
}
|
||||
val controller = Controller2()
|
||||
controller.injectDependencies(kodein)
|
||||
|
||||
assertThat(controller.service).isNotNull
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.baeldung.kotlin;
|
||||
|
||||
import org.junit.Test
|
||||
import org.mockito.Mockito
|
||||
|
||||
class LibraryManagementTest {
|
||||
@Test(expected = IllegalStateException::class)
|
||||
fun whenBookIsNotAvailable_thenAnExceptionIsThrown() {
|
||||
val mockBookService = Mockito.mock(BookService::class.java)
|
||||
|
||||
Mockito.`when`(mockBookService.inStock(100)).thenReturn(false)
|
||||
|
||||
val manager = LendBookManager(mockBookService)
|
||||
|
||||
manager.checkout(100, 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBookIsAvailable_thenLendMethodIsCalled() {
|
||||
val mockBookService = Mockito.mock(BookService::class.java)
|
||||
|
||||
Mockito.`when`(mockBookService.inStock(100)).thenReturn(true)
|
||||
|
||||
val manager = LendBookManager(mockBookService)
|
||||
|
||||
manager.checkout(100, 1)
|
||||
|
||||
Mockito.verify(mockBookService).lend(100, 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.baeldung.kotlin;
|
||||
|
||||
import com.nhaarman.mockito_kotlin.mock
|
||||
import com.nhaarman.mockito_kotlin.verify
|
||||
import com.nhaarman.mockito_kotlin.whenever
|
||||
import org.junit.Test
|
||||
|
||||
class LibraryManagementTestMockitoKotlin {
|
||||
@Test(expected = IllegalStateException::class)
|
||||
fun whenBookIsNotAvailable_thenAnExceptionIsThrown() {
|
||||
val mockBookService = mock<BookService>()
|
||||
|
||||
whenever(mockBookService.inStock(100)).thenReturn(false)
|
||||
|
||||
val manager = LendBookManager(mockBookService)
|
||||
|
||||
manager.checkout(100, 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenBookIsAvailable_thenLendMethodIsCalled() {
|
||||
val mockBookService : BookService = mock()
|
||||
|
||||
whenever(mockBookService.inStock(100)).thenReturn(true)
|
||||
|
||||
val manager = LendBookManager(mockBookService)
|
||||
|
||||
manager.checkout(100, 1)
|
||||
|
||||
verify(mockBookService).lend(100, 1)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user