@Test
public void shouldHandleSet() {

  Codec<Set<Integer>> setIntCodec = mapper.codecFor(new RawSet(primitive(INT)));
  Codec<Set<Integer>> setIntCodec2 = mapper.codecFor(new RawSet(primitive(INT)));
  assertThat(setIntCodec).isSameAs(setIntCodec2);
  Set<Integer> s = new LinkedHashSet<>();
  s.add(1);
  s.add(2);
  s.add(-40);
  String setStr = "0x000000030000000400000001000000040000000200000004ffffffd8";
  encodeAndDecode(setIntCodec, Collections.singleton(77), "0x00000001000000040000004d");
  encodeAndDecode(setIntCodec, s, setStr);
  encodeAndDecode(setIntCodec, Collections.emptySet(), "0x00000000");
  encodeAndDecode(setIntCodec, null, null, Collections.emptySet());
  encodeObjectAndDecode(setIntCodec, s, setStr, s);
  encodeObjectAndDecode(setIntCodec, new ArrayList<>(s), setStr, s);
  encodeObjectAndDecode(setIntCodec, null, null, Collections.emptySet());
  encodeObjectAndDecode(setIntCodec, Optional.of(12), null, Collections.emptySet());
  // Null value in Set
  try {
    encodeAndDecode(setIntCodec, Collections.singleton(null), null);
    fail("Expected NPE");
  } catch (NullPointerException e) { // expected
  }
  // Set not matching type for Codec
  try {
    Set stringSet = new LinkedHashSet<>();
    stringSet.add("hello");
    encodeAndDecode(setIntCodec, stringSet, "");
    fail("Expected InvalidTypeException");
  } catch (InvalidTypeException e) {
    assertThat(e.getCause()).isInstanceOf(ClassCastException.class);
  }
  // Underflow while decoding
  try {
    ByteBuffer buf = setIntCodec.encode(s);
    // half limit so buffer is truncated.
    buf.limit(buf.limit() / 2);
    setIntCodec.decode(buf);
    fail("Expected InvalidTypeException");
  } catch (InvalidTypeException e) {
    assertThat(e.getCause()).isInstanceOf(BufferUnderflowException.class);
  }
  // Values of set should be mapped using encodeObject
  // In this case we have a codec that calls for set<int> but we give it a Set<String>.
  // The codec should properly convert to Set<Integer> from Set<String>.
  Set<String> stringSet = new LinkedHashSet<>();
  stringSet.add("1");
  stringSet.add("2");
  stringSet.add("-40");
  encodeObjectAndDecode(setIntCodec, stringSet, setStr, s);
}