View Javadoc
1   /*
2    * Licensed under the GPL License. You may not use this file except in compliance with the License.
3    * You may obtain a copy of the License at
4    *
5    *   https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
6    *
7    * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
8    * WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
9    * PURPOSE.
10   */
11  package psiprobe.tools;
12  
13  import static org.junit.jupiter.api.Assertions.assertEquals;
14  
15  import java.lang.reflect.Field;
16  
17  import org.junit.jupiter.api.Test;
18  
19  /**
20   * Tests for {@link SimpleAccessor}.
21   */
22  class SimpleAccessorTest {
23  
24    /** Test target class with a public and a private field. */
25    static class Target {
26      public String publicField = "public";
27      private String privateField = "private";
28    }
29  
30    @Test
31    void testGetPublicField() throws NoSuchFieldException {
32      SimpleAccessor accessor = new SimpleAccessor();
33      Target target = new Target();
34      Field field = Target.class.getDeclaredField("publicField");
35      Object value = accessor.get(target, field);
36      assertEquals("public", value);
37    }
38  
39    @Test
40    void testGetPrivateField() throws NoSuchFieldException {
41      SimpleAccessor accessor = new SimpleAccessor();
42      Target target = new Target();
43      Field field = Target.class.getDeclaredField("privateField");
44      // private field can be accessed after setAccessible(true)
45      Object value = accessor.get(target, field);
46      assertEquals("private", value);
47    }
48  
49    @Test
50    void testGetStaticField() throws NoSuchFieldException {
51      SimpleAccessor accessor = new SimpleAccessor();
52      // Test with a static field from Integer (which can be accessed with null object)
53      Field field = Integer.class.getDeclaredField("MAX_VALUE");
54      Object value = accessor.get(null, field);
55      assertEquals(Integer.MAX_VALUE, value);
56    }
57  }