WebActionRequestBodyAdapter implements JsonDeserializer<String>, JsonSerializer<String> { @Override public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { if (json.isJsonNull()) { return null; } else if (json.isJsonPrimitive()) { return json.getAsString(); } else if (json.isJsonObject() && json.getAsJsonObject().size() == 0) { return null; } throw new IllegalStateException( "expected a string, null, or an empty object as request body but got" + this.getClass()); }  @Override String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context); @Override JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context);  }
@Test public void deser_NullGiven_ShouldReturnNull() { JsonElement json = mock(JsonElement.class); when(json.isJsonNull()).thenReturn(true); assertNull(deserializer.deserialize(json, null, null)); }
@Test public void deser_PrimitiveGiven_ShouldReturnAsString() { JsonElement json = mock(JsonElement.class); when(json.isJsonNull()).thenReturn(false); when(json.isJsonPrimitive()).thenReturn(true); when(json.getAsString()).thenReturn("whatever"); assertEquals("whatever", deserializer.deserialize(json, null, null)); }
@Test public void deser_EmptyObjectGiven_ShouldReturnNull() { JsonElement json = mock(JsonElement.class); when(json.isJsonNull()).thenReturn(false); when(json.isJsonPrimitive()).thenReturn(false); when(json.isJsonObject()).thenReturn(true); when(json.getAsJsonObject()).thenReturn(new JsonObject()); assertNull(deserializer.deserialize(json, null, null)); }
@Test public void deser_NonEmptyObjectGiven_ShouldFail() { JsonElement json = mock(JsonElement.class); when(json.isJsonNull()).thenReturn(false); when(json.isJsonPrimitive()).thenReturn(false); when(json.isJsonObject()).thenReturn(true); JsonObject object = new JsonObject(); object.addProperty("what", "ever"); when(json.getAsJsonObject()).thenReturn(object); assertThrows(IllegalStateException.class, () -> deserializer.deserialize(json, null, null)); }
@Test public void deser_UnsupportedTypeGiven_ShouldFail() { JsonElement json = mock(JsonElement.class); when(json.isJsonNull()).thenReturn(false); when(json.isJsonPrimitive()).thenReturn(false); when(json.isJsonObject()).thenReturn(false); assertThrows(IllegalStateException.class, () -> deserializer.deserialize(json, null, null)); }
@Test public void deser_NoObjectButObjectEntriesGiven_ShouldFail() { JsonElement json = mock(JsonElement.class); when(json.isJsonNull()).thenReturn(false); when(json.isJsonPrimitive()).thenReturn(false); when(json.isJsonObject()).thenReturn(false); when(json.getAsJsonObject()).thenReturn(new JsonObject()); assertThrows(IllegalStateException.class, () -> deserializer.deserialize(json, null, null)); }