From 32be9b9a2e32a2e6f6e3c575eb1b334b6ac6bad4 Mon Sep 17 00:00:00 2001 From: "Erik C. Thauvin" Date: Wed, 26 May 2021 18:31:36 -0700 Subject: [PATCH] Added toJson/toString functions. --- .../net/thauvin/erik/crypto/CryptoPrice.kt | 23 ++++++++++++++++++- .../thauvin/erik/crypto/CryptoPriceTest.kt | 20 +++++++++++++--- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/main/kotlin/net/thauvin/erik/crypto/CryptoPrice.kt b/src/main/kotlin/net/thauvin/erik/crypto/CryptoPrice.kt index 168a3ae..c51c0c5 100644 --- a/src/main/kotlin/net/thauvin/erik/crypto/CryptoPrice.kt +++ b/src/main/kotlin/net/thauvin/erik/crypto/CryptoPrice.kt @@ -37,6 +37,7 @@ import okhttp3.OkHttpClient import okhttp3.Request import org.json.JSONException import org.json.JSONObject +import org.json.JSONStringer import java.io.IOException import java.math.BigDecimal import java.text.NumberFormat @@ -149,5 +150,25 @@ open class CryptoPrice(val base: String, val currency: String, val amount: BigDe it.setMinimumFractionDigits(minFractionDigits) it.format(amount) } - } + } + + /** + * Return a JSON representation of the [CryptoPrice]. + */ + fun toJson(): String { + return JSONStringer() + .`object`().key("data") + .`object`() + .key("base").value(base) + .key("currency").value(currency) + .key("amount").value(amount.toString()) + .endObject() + .endObject() + .toString() + } + + /** + * Return a JSON respresentation of the [CryptoPrice]. + */ + override fun toString(): String = toJson() } diff --git a/src/test/kotlin/net/thauvin/erik/crypto/CryptoPriceTest.kt b/src/test/kotlin/net/thauvin/erik/crypto/CryptoPriceTest.kt index bbf6166..9f0a777 100644 --- a/src/test/kotlin/net/thauvin/erik/crypto/CryptoPriceTest.kt +++ b/src/test/kotlin/net/thauvin/erik/crypto/CryptoPriceTest.kt @@ -12,9 +12,11 @@ import kotlin.test.assertFailsWith import kotlin.test.assertTrue /** - * The `CryptoPriceTest` class. + * [CryptoPrice] Tests */ class CryptoPriceTest { + val jsonData = "{\"data\":{\"base\":\"BTC\",\"currency\":\"USD\",\"amount\":\"%s\"}}" + @Test @Throws(CryptoException::class) fun testBTCPrice() { @@ -108,15 +110,27 @@ class CryptoPriceTest { assertEquals("$12,345.6", usd.toCurrency(minFractionDigits = 0), "minFractionDigits = 0") } + @Test + fun testToJson() { + listOf("1234.5", "1234.56", "1234.567").forEach { + val json = jsonData.format(it) + with(json.toPrice()) { + assertEquals(json, toJson(), "toJson($it)") + assertEquals(json, toString(), "toString($it)") + } + } + } + + @Test @Throws(CryptoException::class) fun testToPrice() { val d = "57515.60" - val json = "{\"data\":{\"base\":\"BTC\",\"currency\":\"USD\",\"amount\":\"$d\"}}" + val json = jsonData.format(d) val price = json.toPrice() assertEquals("BTC", price.base, "base is BTC") assertEquals("USD", price.currency, "currency is USD") - assertEquals(d, price.amount.toString(), "amount is 57515.60") + assertEquals(d, price.amount.toString(), "amount is $d") assertFailsWith( message = "double conversion did not fail",