|
| 1 | +package com.fasterxml.jackson.databind.creators; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.annotation.JsonCreator; |
| 4 | +import com.fasterxml.jackson.annotation.JsonProperty; |
| 5 | +import com.fasterxml.jackson.databind.*; |
| 6 | + |
| 7 | +/** |
| 8 | + * Tests to ensure that deserialization fails when a bean property has a null value |
| 9 | + * Relates to <a href="https://github.com/FasterXML/jackson-databind/issues/988">issue #988</a> |
| 10 | + */ |
| 11 | +public class FailOnNullCreatorTest extends BaseMapTest |
| 12 | +{ |
| 13 | + static class Person { |
| 14 | + String name; |
| 15 | + Integer age; |
| 16 | + |
| 17 | + @JsonCreator |
| 18 | + public Person(@JsonProperty(value="name") String name, |
| 19 | + @JsonProperty(value="age") int age) |
| 20 | + { |
| 21 | + this.name = name; |
| 22 | + this.age = age; |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + private final ObjectReader POINT_READER = objectMapper().readerFor(Person.class); |
| 27 | + |
| 28 | + public void testRequiredNonNullParam() throws Exception |
| 29 | + { |
| 30 | + Person p; |
| 31 | + // First: fine if feature is not enabled |
| 32 | + p = POINT_READER.readValue(aposToQuotes("{}")); |
| 33 | + assertEquals(null, p.name); |
| 34 | + assertEquals(Integer.valueOf(0), p.age); |
| 35 | + |
| 36 | + // Second: fine if feature is enabled but default value is not null |
| 37 | + ObjectReader r = POINT_READER.with(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES); |
| 38 | + p = POINT_READER.readValue(aposToQuotes("{'name':'John', 'age': null}")); |
| 39 | + assertEquals("John", p.name); |
| 40 | + assertEquals(Integer.valueOf(0), p.age); |
| 41 | + |
| 42 | + // Third: throws exception if property is missing |
| 43 | + try { |
| 44 | + r.readValue(aposToQuotes("{}")); |
| 45 | + fail("Should not pass third test"); |
| 46 | + } catch (JsonMappingException e) { |
| 47 | + verifyException(e, "Null value for creator property 'name'"); |
| 48 | + } |
| 49 | + |
| 50 | + // Fourth: throws exception if property is set to null explicitly |
| 51 | + try { |
| 52 | + r.readValue(aposToQuotes("{'age': 5, 'name': null}")); |
| 53 | + fail("Should not pass fourth test"); |
| 54 | + } catch (JsonMappingException e) { |
| 55 | + verifyException(e, "Null value for creator property 'name'"); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | +} |
0 commit comments