1 package com.fasterxml.jackson.databind.util; 2 3 import java.util.List; 4 5 import com.fasterxml.jackson.databind.BaseMapTest; 6 import com.fasterxml.jackson.databind.ObjectMapper; 7 import com.fasterxml.jackson.databind.SerializationConfig; 8 import com.fasterxml.jackson.databind.SerializationFeature; 9 10 public class EnumValuesTest extends BaseMapTest 11 { 12 enum ABC { 13 A("A"), 14 B("b"), 15 C("C"); 16 17 private final String desc; 18 ABC(String d)19 private ABC(String d) { desc = d; } 20 21 @Override toString()22 public String toString() { return desc; } 23 } 24 25 final ObjectMapper MAPPER = new ObjectMapper(); 26 27 @SuppressWarnings("unchecked") testConstructFromName()28 public void testConstructFromName() { 29 SerializationConfig cfg = MAPPER.getSerializationConfig() 30 .without(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); 31 Class<Enum<?>> enumClass = (Class<Enum<?>>)(Class<?>) ABC.class; 32 EnumValues values = EnumValues.construct(cfg, enumClass); 33 assertEquals("A", values.serializedValueFor(ABC.A).toString()); 34 assertEquals("B", values.serializedValueFor(ABC.B).toString()); 35 assertEquals("C", values.serializedValueFor(ABC.C).toString()); 36 assertEquals(3, values.values().size()); 37 assertEquals(3, values.internalMap().size()); 38 } 39 40 @SuppressWarnings("unchecked") testConstructWithToString()41 public void testConstructWithToString() { 42 SerializationConfig cfg = MAPPER.getSerializationConfig() 43 .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); 44 Class<Enum<?>> enumClass = (Class<Enum<?>>)(Class<?>) ABC.class; 45 EnumValues values = EnumValues.construct(cfg, enumClass); 46 assertEquals("A", values.serializedValueFor(ABC.A).toString()); 47 assertEquals("b", values.serializedValueFor(ABC.B).toString()); 48 assertEquals("C", values.serializedValueFor(ABC.C).toString()); 49 assertEquals(3, values.values().size()); 50 assertEquals(3, values.internalMap().size()); 51 } 52 testEnumResolver()53 public void testEnumResolver() 54 { 55 EnumResolver enumRes = EnumResolver.constructUnsafeUsingToString(ABC.class, 56 MAPPER.getSerializationConfig().getAnnotationIntrospector()); 57 assertEquals(ABC.B, enumRes.getEnum(1)); 58 assertNull(enumRes.getEnum(-1)); 59 assertNull(enumRes.getEnum(3)); 60 assertEquals(2, enumRes.lastValidIndex()); 61 List<Enum<?>> enums = enumRes.getEnums(); 62 assertEquals(3, enums.size()); 63 assertEquals(ABC.A, enums.get(0)); 64 assertEquals(ABC.B, enums.get(1)); 65 assertEquals(ABC.C, enums.get(2)); 66 } 67 } 68