OptionalConverter implements PropertyConverter<Optional> { @Override public Optional convert(String value, ConversionContext ctx) { if(value==null){ return Optional.empty(); } try{ Type targetType = ctx.getTargetType().getType(); ParameterizedType pt = (ParameterizedType) targetType; if(String.class.equals(pt.getActualTypeArguments()[0])){ return Optional.of(value); } ConvertQuery converter = new ConvertQuery(value, TypeLiteral.of(pt.getActualTypeArguments()[0])); return Optional.ofNullable(ctx.getConfiguration().adapt(converter)); }catch(Exception e){ throw new ConfigException("Error evaluating config createValue.", e); } }  @Override Optional convert(String value, ConversionContext ctx); @Override boolean equals(Object o); @Override int hashCode();  }
@Test public void nullConversionYieldsEmptyOptional() { ConversionContext context = Mockito.mock(ConversionContext.class); final Optional<?> result = new OptionalConverter().convert(null, context); assertThat(result).isNotNull(); assertThat(result.isPresent()).isFalse(); }
@Test(expected = ConfigException.class) public void emulateExceptionWhenGivenContextIsNull() { ConversionContext context = Mockito.mock(ConversionContext.class); new OptionalConverter().convert("JustATestValueThatIsIgnored", context); }
@Test public void testOptionalString() { TypeLiteral<List<String>> listOfStringTypeLiteral = new TypeLiteral<List<String>>() { }; ConversionContext context = new ConversionContext.Builder("testOptionalString", listOfStringTypeLiteral).build(); final Optional<String> result = new OptionalConverter().convert("astring", context); assertThat(result).isNotNull(); assertThat(result.isPresent()).isTrue(); assertThat(result.get()).isEqualTo("astring"); }
@Test public void testOptionalInteger() { TypeLiteral<List<Integer>> listOfIntegerTypeLiteral = new TypeLiteral<List<Integer>>() { }; ConversionContext context = new ConversionContext.Builder("testOptionalInteger", listOfIntegerTypeLiteral) .setConfiguration(Configuration.current()) .build(); final Optional<Integer> result = new OptionalConverter().convert("11", context); assertThat(result).isNotNull(); assertThat(result.isPresent()).isTrue(); assertThat(result.get().intValue()).isEqualTo(11); }