ResponseBeanReader { public Object fromJSON(Type responseType, byte[] body) throws IOException { if (void.class == responseType) return null; Class<?> beanClass = ContextHelper.responseBeanClass(responseType); Context<Object> context = ContextHelper.context(this.context, beanClass); Object bean = context.reader.fromJSON(body); if (GenericTypes.isOptional(responseType)) { if (bean == null) return Optional.empty(); context.validator.validate(bean, false); return Optional.of(bean); } else { context.validator.validate(bean, false); return bean; } } ResponseBeanReader(); void register(Type responseType, BeanClassValidator validator); Object fromJSON(Type responseType, byte[] body);  }
@Test void fromJSONWithEmptyOptional() throws IOException { @SuppressWarnings("unchecked") var parsedBean = (Optional<TestBean>) reader.fromJSON(Types.optional(TestBean.class), Strings.bytes("null")); assertThat(parsedBean).isNotPresent(); }
@Test void fromJSONWithOptional() throws IOException { var bean = new TestBean(); bean.intField = 3; @SuppressWarnings("unchecked") var parsedBean = (Optional<TestBean>) reader.fromJSON(Types.optional(TestBean.class), Strings.bytes(JSON.toJSON(bean))); assertThat(parsedBean).get().usingRecursiveComparison().isEqualTo(bean); }
@Test void fromJSONWithValidationError() { var bean = new TestBean(); assertThatThrownBy(() -> reader.fromJSON(TestBean.class, Strings.bytes(JSON.toJSON(bean)))) .isInstanceOf(ValidationException.class) .hasMessageContaining("validation failed"); }
@Test void fromJSONWithVoid() throws IOException { assertThat(reader.fromJSON(void.class, null)).isNull(); }
@Test void fromJSON() throws IOException { var bean = new TestBean(); bean.intField = 3; TestBean parsedBean = (TestBean) reader.fromJSON(TestBean.class, Strings.bytes(JSON.toJSON(bean))); assertThat(parsedBean).usingRecursiveComparison().isEqualTo(bean); }
@Test void withUnregisteredBean() { assertThatThrownBy(() -> reader.fromJSON(TestUnregisteredBean.class, new byte[0])) .isInstanceOf(Error.class) .hasMessageContaining("bean class is not registered"); }