From 3ae51c35808e431f22abfa322b95e0d7ba09a050 Mon Sep 17 00:00:00 2001 From: sonny Date: Tue, 11 Feb 2020 18:08:19 +0800 Subject: [PATCH] add assertAsMap --- .../main/java/com/aliyun/teautil/Common.java | 12 ++++++++++ .../java/com/aliyun/teautil/CommonTest.java | 24 +++++++++++++++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/java/src/main/java/com/aliyun/teautil/Common.java b/java/src/main/java/com/aliyun/teautil/Common.java index 3db40234..00ed21dc 100644 --- a/java/src/main/java/com/aliyun/teautil/Common.java +++ b/java/src/main/java/com/aliyun/teautil/Common.java @@ -39,6 +39,18 @@ public static Object parseJSON(String json) { return new Gson().fromJson(json, Map.class); } + /** + * Assert a value, if it is a map, return it, otherwise throws + * + * @return the map value + */ + public static Map assertAsMap(Object object) { + if (null != object && !List.class.isAssignableFrom(object.getClass())) { + return new Gson().fromJson(String.valueOf(object), Map.class); + } + throw new RuntimeException("The value is not a object"); + } + /** * Read data from a readable stream, and compose it to a bytes * diff --git a/java/src/test/java/com/aliyun/teautil/CommonTest.java b/java/src/test/java/com/aliyun/teautil/CommonTest.java index 82e829cc..431ffe07 100644 --- a/java/src/test/java/com/aliyun/teautil/CommonTest.java +++ b/java/src/test/java/com/aliyun/teautil/CommonTest.java @@ -9,10 +9,7 @@ import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.SimpleTimeZone; +import java.util.*; public class CommonTest { @Test @@ -134,4 +131,23 @@ public void stringifyMapValueTest() { Assert.assertEquals("string", result.get("testString")); Assert.assertEquals("1", result.get("testNum")); } + + @Test + public void assertAsMapTest() { + try { + Common.assertAsMap(new ArrayList<>()); + Assert.fail(); + }catch (Exception e) { + Assert.assertEquals("The value is not a object", e.getMessage()); + } + + try { + Common.assertAsMap(null); + Assert.fail(); + }catch (Exception e) { + Assert.assertEquals("The value is not a object", e.getMessage()); + } + + Assert.assertEquals("test", Common.assertAsMap("{\"test\":\"test\"}").get("test")); + } }