TypeCachingJaxb implements Jaxb { public <T> void marshal(T object, OutputStream out, Charset charset) throws Exception { Jaxb jaxb; if(object instanceof Classes) { Set<Class<?>> classes = ((Classes) object).getClasses(); jaxb = get(classes); }else{ jaxb = get(Collections.<Class<?>>singleton(object.getClass())); } jaxb.<T>marshal(object, out, charset); } TypeCachingJaxb(CRestConfig crestConfig, Class<?> source); void marshal(T object, OutputStream out, Charset charset); T unmarshal(Class<T> type, Type genericType, Reader reader);  }
@Test public void shouldCreateJaxbInstanceForFirstCallFromSimpleObjectAndReuseItForMarshallCallWithSameObjectType() throws Exception { Object toMarshal = new Object(); Object toMarshal2 = new Object(); String toMarshal3 = new String(); OutputStream outputStream = mock(OutputStream.class); Charset charset = Values.UTF8; Jaxb mockJaxb = mock(Jaxb.class); Jaxb mockJaxb2 = mock(Jaxb.class); mockStatic(JaxbFactory.class); when(JaxbFactory.create(mockCRestConfig, getClass(), new Class<?>[]{Object.class})).thenReturn(mockJaxb); when(JaxbFactory.create(mockCRestConfig, getClass(), new Class<?>[]{String.class})).thenReturn(mockJaxb2); toTest.marshal(toMarshal,outputStream,charset); toTest.marshal(toMarshal2,outputStream,charset); toTest.marshal(toMarshal3,outputStream,charset); verify(mockJaxb).marshal(toMarshal,outputStream,charset); verify(mockJaxb).marshal(toMarshal2,outputStream,charset); verify(mockJaxb2).marshal(toMarshal3,outputStream,charset); }
@Test public void shouldCreateJaxbInstanceForFirstCallFromInstanceOfClassesAndReuseItForMarshallCallWithSameObjectType() throws Exception { Object toMarshal1 = new Object(); Object toMarshal12 = new Object(); MyObject toMarshal2 = new MyObject(); MyObject toMarshal22 = new MyObject(); OutputStream outputStream = mock(OutputStream.class); Charset charset = Values.UTF8; final Jaxb mockJaxb2 = mock(Jaxb.class); Jaxb mockJaxb1 = mock(Jaxb.class); Set<Class<?>> expected = MyObject.classes(); mockStatic(JaxbFactory.class); when(JaxbFactory.create(mockCRestConfig, getClass(), new Class<?>[]{Object.class})).thenReturn(mockJaxb1); when(JaxbFactory.create(mockCRestConfig, getClass(),expected.toArray(new Class<?>[expected.size()]))).thenReturn(mockJaxb2); toTest.marshal(toMarshal1,outputStream,charset); toTest.marshal(toMarshal2,outputStream,charset); toTest.marshal(toMarshal12,outputStream,charset); toTest.marshal(toMarshal22,outputStream,charset); verify(mockJaxb1).marshal(toMarshal1,outputStream,charset); verify(mockJaxb2).marshal(toMarshal2,outputStream,charset); verify(mockJaxb1).marshal(toMarshal12,outputStream,charset); verify(mockJaxb2).marshal(toMarshal22,outputStream,charset); }