Added toJson/toString functions.
This commit is contained in:
parent
65ad0e9982
commit
32be9b9a2e
2 changed files with 39 additions and 4 deletions
|
@ -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
|
||||
|
@ -150,4 +151,24 @@ open class CryptoPrice(val base: String, val currency: String, val amount: BigDe
|
|||
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()
|
||||
}
|
||||
|
|
|
@ -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",
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue