Merge pull request #225 from NightlyNexus/eric/add-null

Disallow Moshi.Builder.add(null)
This commit is contained in:
Jesse Wilson
2017-01-17 18:23:03 -08:00
committed by GitHub
2 changed files with 59 additions and 0 deletions

View File

@@ -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));
}

View File

@@ -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<? extends Annotation> 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())