|
| 1 | +package com.baeldung.jaxb.test; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileReader; |
| 5 | +import java.io.IOException; |
| 6 | +import java.util.Date; |
| 7 | +import java.util.TimeZone; |
| 8 | + |
| 9 | +import javax.xml.bind.JAXBContext; |
| 10 | +import javax.xml.bind.JAXBException; |
| 11 | +import javax.xml.bind.Marshaller; |
| 12 | +import javax.xml.bind.Unmarshaller; |
| 13 | + |
| 14 | +import org.apache.commons.io.FileUtils; |
| 15 | +import org.junit.Assert; |
| 16 | +import org.junit.Before; |
| 17 | +import org.junit.FixMethodOrder; |
| 18 | +import org.junit.Test; |
| 19 | +import org.junit.runners.MethodSorters; |
| 20 | + |
| 21 | +import com.baeldung.jaxb.Book; |
| 22 | + |
| 23 | +@FixMethodOrder(MethodSorters.NAME_ASCENDING) |
| 24 | +public class JaxbTest { |
| 25 | + Book book; |
| 26 | + JAXBContext context; |
| 27 | + |
| 28 | + @Before |
| 29 | + public void before() throws JAXBException { |
| 30 | + book = new Book(); |
| 31 | + book.setId(1L); |
| 32 | + book.setName("Book1"); |
| 33 | + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); |
| 34 | + book.setDate(new Date(1481909329718L)); |
| 35 | + context = JAXBContext.newInstance(Book.class); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + public void marshal() throws JAXBException, IOException { |
| 40 | + Marshaller marshaller = context.createMarshaller(); |
| 41 | + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); |
| 42 | + marshaller.marshal(book, new File("./book.xml")); |
| 43 | + String sampleBookXML = FileUtils.readFileToString(new File("./sample_book.xml"), "UTF-8"); |
| 44 | + String marshallerBookXML = FileUtils.readFileToString(new File("./book.xml"), "UTF-8"); |
| 45 | + Assert.assertEquals(sampleBookXML, marshallerBookXML); |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + public void unMashal() throws JAXBException, IOException { |
| 50 | + Unmarshaller unmarshaller = context.createUnmarshaller(); |
| 51 | + Book unMarshallerbook = (Book) unmarshaller.unmarshal(new FileReader("./book.xml")); |
| 52 | + Assert.assertEquals(book, unMarshallerbook); |
| 53 | + } |
| 54 | +} |
0 commit comments