1 package com.atlassian.sal.api.user;
2
3 import org.junit.Before;
4 import org.junit.Test;
5
6 import javax.xml.bind.JAXBContext;
7 import javax.xml.bind.Marshaller;
8 import javax.xml.bind.Unmarshaller;
9 import javax.xml.bind.annotation.XmlElement;
10 import javax.xml.bind.annotation.XmlRootElement;
11 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
12 import java.io.StringReader;
13 import java.io.StringWriter;
14
15 import static javax.xml.bind.Marshaller.JAXB_FRAGMENT;
16 import static org.hamcrest.Matchers.is;
17 import static org.junit.Assert.assertThat;
18
19 public class TestUserKeyXmlAdapter {
20 private Marshaller marshaller;
21 private Unmarshaller unmarshaller;
22
23 @Before
24 public void setUp() throws Exception {
25 JAXBContext jaxbContext = JAXBContext.newInstance(TestEntity.class);
26
27 marshaller = jaxbContext.createMarshaller();
28 marshaller.setProperty(JAXB_FRAGMENT, true);
29
30 unmarshaller = jaxbContext.createUnmarshaller();
31 }
32
33 @Test
34 public void xmlAdapterMarshalsAndUnMarshalsCorrectly() throws Exception {
35 final TestEntity testEntity = new TestEntity();
36 testEntity.userKey = new UserKey("abc");
37
38 final StringWriter buffer = new StringWriter();
39 marshaller.marshal(testEntity, buffer);
40
41 assertThat(buffer.toString(), is("<testEntity><userKey>abc</userKey></testEntity>"));
42
43 final TestEntity unmarshalledEntity = (TestEntity) unmarshaller.unmarshal(new StringReader(buffer.toString()));
44
45 assertThat(unmarshalledEntity.userKey, is(new UserKey("abc")));
46 }
47
48 @XmlRootElement
49 public static class TestEntity {
50 @XmlJavaTypeAdapter(UserKeyXmlAdapter.class)
51 @XmlElement
52 UserKey userKey;
53 }
54 }