diff --git a/moshi/src/main/java/com/squareup/moshi/Moshi.java b/moshi/src/main/java/com/squareup/moshi/Moshi.java index 64844ed..39e83f3 100644 --- a/moshi/src/main/java/com/squareup/moshi/Moshi.java +++ b/moshi/src/main/java/com/squareup/moshi/Moshi.java @@ -182,11 +182,13 @@ public final class Moshi { } public Builder add(JsonAdapter.Factory factory) { + if (factory == null) throw new IllegalArgumentException("factory == null"); factories.add(factory); return this; } public Builder add(Object adapter) { + if (adapter == null) throw new IllegalArgumentException("adapter == null"); return add(AdapterMethodsFactory.get(adapter)); } diff --git a/moshi/src/test/java/com/squareup/moshi/MoshiTest.java b/moshi/src/test/java/com/squareup/moshi/MoshiTest.java index ab8b6f5..cb0169c 100644 --- a/moshi/src/test/java/com/squareup/moshi/MoshiTest.java +++ b/moshi/src/test/java/com/squareup/moshi/MoshiTest.java @@ -532,6 +532,63 @@ public final class MoshiTest { assertThat(adapter.toJson(null)).isEqualTo("null"); } + @Test public void addNullFails() throws Exception { + JsonAdapter jsonAdapter = new JsonAdapter() { + @Override public Object fromJson(JsonReader reader) throws IOException { + throw new AssertionError(); + } + + @Override public void toJson(JsonWriter writer, Object value) throws IOException { + throw new AssertionError(); + } + }; + Type type = Object.class; + Class annotation = Annotation.class; + Moshi.Builder builder = new Moshi.Builder(); + try { + builder.add((null)); + fail(); + } catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("factory == null"); + } + try { + builder.add((Object) null); + fail(); + } catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("adapter == null"); + } + try { + builder.add(null, null); + fail(); + } catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("type == null"); + } + try { + builder.add(type, null); + fail(); + } catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("jsonAdapter == null"); + } + try { + builder.add(null, null, null); + fail(); + } catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("type == null"); + } + try { + builder.add(type, null, null); + fail(); + } catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("annotation == null"); + } + try { + builder.add(type, annotation, null); + fail(); + } catch (IllegalArgumentException expected) { + assertThat(expected).hasMessage("jsonAdapter == null"); + } + } + @Test public void customJsonAdapter() throws Exception { Moshi moshi = new Moshi.Builder() .add(Pizza.class, new PizzaAdapter())