-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathReflectorTest.java
More file actions
224 lines (173 loc) · 9.71 KB
/
ReflectorTest.java
File metadata and controls
224 lines (173 loc) · 9.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package com.github.nylle.javafixture;
import com.github.nylle.javafixture.testobjects.TestObjectWithJakartaValidationAnnotations;
import com.github.nylle.javafixture.testobjects.TestObjectWithJakartaValidationAnnotationsOnMethod;
import com.github.nylle.javafixture.testobjects.inheritance.GenericChild;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import jakarta.validation.constraints.Size;
import java.beans.IntrospectionException;
import java.lang.reflect.Field;
import java.lang.reflect.InaccessibleObjectException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ReflectorTest {
@Nested
@DisplayName("when validating a customisation")
class ValidateCustomization {
@Test
@DisplayName("with existing fields, nothing happens")
void validCustomization() {
var sut = new Reflector<>(new GenericChild<String>(), new SpecimenType<>(){});
var validCustomisation = new CustomizationContext(List.of(), Map.of("baseField.subField", "foo"), false);
assertThatCode(() -> sut.validateCustomization(validCustomisation))
.doesNotThrowAnyException();
}
@Test
@DisplayName("with any missing fields, an exception is thrown")
void invalidCustomization() {
var sut = new Reflector<>(new GenericChild<String>(), new SpecimenType<>() {});
var invalidCustomisation = new CustomizationContext(List.of(), Map.of("nonExistingField.subField", "foo"), false);
assertThatExceptionOfType(CustomizationException.class)
.isThrownBy(() -> sut.validateCustomization(invalidCustomisation))
.withMessage("Cannot customize field 'nonExistingField': Field not found in class 'com.github.nylle.javafixture.testobjects.inheritance.GenericChild<java.lang.String>'.")
.withNoCause();
}
@Test
@DisplayName("to set duplicate fields, an exception is thrown")
void customizingDuplicateFields() {
var sut = new Reflector<>(new GenericChild<String>(), new SpecimenType<>(){});
Map<String, Object> customization = Map.of("fieldIn2Classes.subField", 100.0);
var invalidCustomisation = new CustomizationContext(List.of(), customization, false);
assertThatExceptionOfType(CustomizationException.class)
.isThrownBy(() -> sut.validateCustomization(invalidCustomisation))
.withMessageContaining("Cannot customize field 'fieldIn2Classes'. Duplicate field names found:")
.withMessageContaining("private java.lang.Double com.github.nylle.javafixture.testobjects.inheritance.GenericParent.fieldIn2Classes")
.withMessageContaining("private java.lang.Integer com.github.nylle.javafixture.testobjects.inheritance.GenericBase.fieldIn2Classes")
.withNoCause();
}
@Test
@DisplayName("to omit duplicate fields, an exception is thrown")
void omittingDuplicateFields() {
var sut = new Reflector<>(new GenericChild<String>(), new SpecimenType<>(){});
var omitting = List.of("fieldIn2Classes.subField");
var invalidCustomisation = new CustomizationContext(omitting, Map.of(), false);
assertThatExceptionOfType(CustomizationException.class)
.isThrownBy(() -> sut.validateCustomization(invalidCustomisation))
.withMessageContaining("Cannot customize field 'fieldIn2Classes'. Duplicate field names found:")
.withMessageContaining("private java.lang.Double com.github.nylle.javafixture.testobjects.inheritance.GenericParent.fieldIn2Classes")
.withMessageContaining("private java.lang.Integer com.github.nylle.javafixture.testobjects.inheritance.GenericBase.fieldIn2Classes")
.withNoCause();
}
}
@Nested
@DisplayName("when setting a field via reflection")
class SetField {
private String stringField;
private int primitiveField;
@DisplayName("an Object field can be set")
@Test
void setObject() throws Exception {
var field = this.getClass().getDeclaredField("stringField");
var sut = new Reflector<>(this, new SpecimenType<>(){});
sut.setField(field, "new value");
assertThat(stringField).isEqualTo("new value");
}
@DisplayName("an Object field can be set to null")
@Test
void setObjectToNull() throws Exception {
stringField = "before";
var field = this.getClass().getDeclaredField("stringField");
var sut = new Reflector<>(this, new SpecimenType<>(){});
sut.setField(field, null);
assertThat(stringField).isNull();
}
@DisplayName("a primitive field can be set")
@Test
void setPrimitiveField() throws Exception {
var field = this.getClass().getDeclaredField("primitiveField");
var sut = new Reflector<>(this, new SpecimenType<>(){});
sut.setField(field, 4);
assertThat(primitiveField).isEqualTo(4);
}
@DisplayName("setting a primitive field to null keeps the default value")
@Test
void setPrimitiveFieldToNull() throws Exception {
var field = this.getClass().getDeclaredField("primitiveField");
var sut = new Reflector<>(this, new SpecimenType<>(){});
sut.setField(field, null);
assertThat(primitiveField).isEqualTo(0);
}
@DisplayName("an IllegalAccessException is turned into a SpecimenException")
@Test
void catchIllegalAccessException() throws Exception {
var mockedField = Mockito.mock(Field.class);
doReturn(this.getClass()).when(mockedField).getType();
var sut = new Reflector<>("", new SpecimenType<>(){});
doThrow(new IllegalAccessException("expected")).when(mockedField).set(any(), any());
assertThatExceptionOfType(SpecimenException.class)
.isThrownBy(() -> sut.setField(mockedField, ""));
}
@DisplayName("a SecurityException is turned into a SpecimenException")
@Test
void catchSecurityException() {
var mockedField = Mockito.mock(Field.class);
doReturn(this.getClass()).when(mockedField).getType();
var sut = new Reflector<>("", new SpecimenType<>(){});
doThrow(new SecurityException("expected")).when(mockedField).setAccessible(true);
assertThatExceptionOfType(SpecimenException.class)
.isThrownBy(() -> sut.setField(mockedField, ""));
}
@DisplayName("an InaccessibleObjectException is turned into a SpecimenException")
@Test
void catchInaccessibleObjectException() {
var mockedField = Mockito.mock(Field.class);
doReturn(this.getClass()).when(mockedField).getType();
var sut = new Reflector<>("", new SpecimenType<>(){});
doThrow(new InaccessibleObjectException("expected")).when(mockedField).setAccessible(true);
assertThatExceptionOfType(SpecimenException.class)
.isThrownBy(() -> sut.setField(mockedField, ""));
}
}
@Nested
class GetFieldAnnotations {
@Test
void returnsSizeAnnotationOnPrivateField() {
var sut = new Reflector<>(new TestObjectWithJakartaValidationAnnotations(), new SpecimenType<>(){});
var field = sut.getDeclaredFields().filter(x -> x.getName().equals("withMinMaxAnnotation")).findFirst().get();
var actual = Arrays.stream(sut.getFieldAnnotations(field)).collect(Collectors.toList());
assertThat(actual).hasSize(1);
assertThat(actual.get(0).annotationType()).isEqualTo(Size.class);
}
@Test
void returnsSizeAnnotationOnGetter() {
var sut = new Reflector<>(new TestObjectWithJakartaValidationAnnotationsOnMethod(), new SpecimenType<>(){});
var field = sut.getDeclaredFields().filter(x -> x.getName().equals("withMinMaxAnnotation")).findFirst().get();
var actual = Arrays.stream(sut.getFieldAnnotations(field)).collect(Collectors.toList());
assertThat(actual).hasSize(1);
assertThat(actual.get(0).annotationType()).isEqualTo(Size.class);
}
@Test
void returnsSizeAnnotationOnFieldIfGetterThrowsIntrospectionException() {
var sut = new Reflector<>(new TestObjectWithJakartaValidationAnnotations(), new SpecimenType<>(){});
var expected = sut.getDeclaredFields().filter(x -> x.getName().equals("withMinMaxAnnotation")).findFirst().get().getAnnotations();
var throwingField = mock(Field.class);
when(throwingField.getModifiers()).thenAnswer(x -> { throw new IntrospectionException("expected for test"); });
when(throwingField.getAnnotations()).thenReturn(expected);
var actual = Arrays.stream(sut.getFieldAnnotations(throwingField)).collect(Collectors.toList());
assertThat(actual).hasSize(1);
assertThat(actual.get(0).annotationType()).isEqualTo(Size.class);
}
}
}