|
| 1 | +package io.jooby.spi; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.*; |
| 4 | + |
| 5 | +import java.util.function.Consumer; |
| 6 | + |
| 7 | +import org.junit.jupiter.api.AfterAll; |
| 8 | +import org.junit.jupiter.api.Test; |
| 9 | + |
| 10 | +import io.jooby.MissingValueException; |
| 11 | +import io.jooby.QueryString; |
| 12 | +import io.jooby.internal.UrlParser; |
| 13 | + |
| 14 | + |
| 15 | +class ValueConvertersTest { |
| 16 | + |
| 17 | + @AfterAll |
| 18 | + static void restoreFromServiceLoader() { |
| 19 | + //Restore ValueConvert list for other unit tests. |
| 20 | + ValueConverters.getInstance().clear().fromServiceLoader(); |
| 21 | + } |
| 22 | + |
| 23 | + @Test |
| 24 | + void testConvert() { |
| 25 | + ValueConverters.getInstance() |
| 26 | + .clear() |
| 27 | + .add((value, type) -> { |
| 28 | + if (type == MyValue.class) { |
| 29 | + MyValue mv = new MyValue(); |
| 30 | + // we have chosen simple parameters names to make sure we don't get a false positve |
| 31 | + // from the reflection converter. |
| 32 | + mv.name = value.get("n").value(); |
| 33 | + //TODO: ValueContainer probably should have primitive convert methods. |
| 34 | + mv.order = Integer.parseInt(value.get("o").value()); |
| 35 | + return mv; |
| 36 | + } |
| 37 | + return null; |
| 38 | + }); |
| 39 | + queryString("n=stuff&o=1", queryString -> { |
| 40 | + MyValue mv = queryString.to(MyValue.class); |
| 41 | + assertEquals("stuff", mv.name); |
| 42 | + assertEquals(1, mv.order); |
| 43 | + }); |
| 44 | + queryString("n=stuff&missingOrder=1", queryString -> { |
| 45 | + try { |
| 46 | + queryString.to(MyValue.class); |
| 47 | + fail(); |
| 48 | + } |
| 49 | + catch (MissingValueException mve) { |
| 50 | + assertEquals("Missing value: 'o'", mve.getMessage()); |
| 51 | + } |
| 52 | + }); |
| 53 | + } |
| 54 | + |
| 55 | + static class MyValue { |
| 56 | + public String name; |
| 57 | + public int order; |
| 58 | + } |
| 59 | + |
| 60 | + |
| 61 | + |
| 62 | + private void queryString(String queryString, Consumer<QueryString> consumer) { |
| 63 | + consumer.accept(UrlParser.queryString(queryString)); |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments