View Javadoc

1   /*
2    * Grapht, an open source dependency injector.
3    * Copyright 2014-2015 various contributors (see CONTRIBUTORS.txt)
4    * Copyright 2010-2014 Regents of the University of Minnesota
5    *
6    * This program is free software; you can redistribute it and/or modify
7    * it under the terms of the GNU Lesser General Public License as
8    * published by the Free Software Foundation; either version 2.1 of the
9    * License, or (at your option) any later version.
10   *
11   * This program is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13   * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14   * details.
15   *
16   * You should have received a copy of the GNU General Public License along with
17   * this program; if not, write to the Free Software Foundation, Inc., 51
18   * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19   */
20  package org.grouplens.grapht.util;
21  
22  import org.apache.commons.lang3.SerializationUtils;
23  import org.junit.Test;
24  
25  import java.io.*;
26  import java.lang.reflect.Field;
27  
28  import static org.hamcrest.Matchers.equalTo;
29  import static org.junit.Assert.assertThat;
30  
31  public class FieldProxyTest {
32      private static class TestClass {
33          String foo;
34          int bar;
35      }
36  
37      @Test
38      public void testBasicField() throws NoSuchFieldException, ClassNotFoundException {
39          Field f = TestClass.class.getDeclaredField("foo");
40          FieldProxy proxy = FieldProxy.of(f);
41          assertThat(proxy.resolve(), equalTo(f));
42      }
43  
44      @Test
45      public void testSerializeField() throws NoSuchFieldException, ClassNotFoundException, IOException {
46          Field f = TestClass.class.getDeclaredField("foo");
47          FieldProxy proxy = roundTrip(f);
48          assertThat(proxy.resolve(), equalTo(f));
49      }
50  
51      @Test
52      public void testSerializePrimitiveField() throws NoSuchFieldException, ClassNotFoundException, IOException {
53          Field f = TestClass.class.getDeclaredField("bar");
54          FieldProxy proxy = roundTrip(f);
55          assertThat(proxy.resolve(), equalTo(f));
56      }
57  
58      /**
59       * Serialize and deserialize a field proxy.
60       * @param fld The field to serialize
61       * @return A field proxy that is the result of serializing a proxy for {@code fld} and
62       * deserializing it.
63       */
64      private FieldProxy roundTrip(Field fld) throws IOException, ClassNotFoundException {
65          FieldProxy proxy = FieldProxy.of(fld);
66          return SerializationUtils.clone(proxy);
67      }
68  }