Skip to content

Commit

Permalink
add assertAsMap
Browse files Browse the repository at this point in the history
  • Loading branch information
atptro authored and JacksonTian committed Feb 11, 2020
1 parent ac238d1 commit 3ae51c3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
12 changes: 12 additions & 0 deletions java/src/main/java/com/aliyun/teautil/Common.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Object> 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
*
Expand Down
24 changes: 20 additions & 4 deletions java/src/test/java/com/aliyun/teautil/CommonTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"));
}
}

0 comments on commit 3ae51c3

Please sign in to comment.