Skip to content

Commit 20a0038

Browse files
committed
Add registerMapAdapter test
1 parent 4d4e173 commit 20a0038

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

library/src/androidTest/java/com/hippo/quickjs/android/TypeAdapterTest.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,13 @@
2020
import org.junit.Test;
2121

2222
import java.lang.reflect.Type;
23+
import java.util.Map;
2324
import java.util.concurrent.atomic.AtomicInteger;
2425

2526
import static org.junit.Assert.assertEquals;
2627

28+
import android.util.ArrayMap;
29+
2730
public class TypeAdapterTest {
2831

2932
@Test
@@ -68,4 +71,55 @@ public TypeAdapter<?> create(QuickJS quickJS, Type type) {
6871
return null;
6972
}
7073
}
74+
75+
@Test
76+
public void registerMapAdapter() {
77+
Type mapType = new JavaType<Map<String, String>>() {}.type;
78+
79+
QuickJS quickJS = new QuickJS.Builder()
80+
.registerTypeAdapter(mapType, new MapTypeAdapter().nullable())
81+
.build();
82+
try (JSRuntime runtime = quickJS.createJSRuntime()) {
83+
try (JSContext context = runtime.createJSContext()) {
84+
Map<String, String> actual = context.evaluate(
85+
"a = { key1: \"value1\", key2: \"value2\" }", "test.js", mapType);
86+
Map<String, String> expected = new ArrayMap<>();
87+
expected.put("key1", "value1");
88+
expected.put("key2", "value2");
89+
assertEquals(expected, actual);
90+
}
91+
}
92+
}
93+
94+
private static class MapTypeAdapter extends TypeAdapter<Map<String, String>> {
95+
@Override
96+
public JSValue toJSValue(JSContext context, Map<String, String> value) {
97+
JSObject jo = context.createJSObject();
98+
value.forEach((k, v) -> {
99+
if (k == null) return;
100+
jo.setProperty(k, context.createJSString(v));
101+
});
102+
return jo;
103+
}
104+
105+
@Override
106+
public Map<String, String> fromJSValue(JSContext context, JSValue value) {
107+
JSObject jo = value.cast(JSObject.class);
108+
JSFunction keysFunction = context.getGlobalObject()
109+
.getProperty("Object").cast(JSObject.class)
110+
.getProperty("keys").cast(JSFunction.class);
111+
112+
TypeAdapter<String[]> adapter = context.quickJS.getAdapter(String[].class);
113+
JSValue keysResult = keysFunction.invoke(null, new JSValue[] { jo });
114+
String[] keys = adapter.fromJSValue(context, keysResult);
115+
116+
Map<String, String> map = new ArrayMap<>(keys.length);
117+
for (String key: keys) {
118+
String val = jo.getProperty(key).cast(JSString.class).getString();
119+
map.put(key, val);
120+
}
121+
122+
return map;
123+
}
124+
}
71125
}

0 commit comments

Comments
 (0)