-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathObjectSpecimen.java
More file actions
75 lines (61 loc) · 3.01 KB
/
ObjectSpecimen.java
File metadata and controls
75 lines (61 loc) · 3.01 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
package com.github.nylle.javafixture.specimen;
import com.github.nylle.javafixture.Context;
import com.github.nylle.javafixture.CustomizationContext;
import com.github.nylle.javafixture.ISpecimen;
import com.github.nylle.javafixture.InstanceFactory;
import com.github.nylle.javafixture.Reflector;
import com.github.nylle.javafixture.SpecimenException;
import com.github.nylle.javafixture.SpecimenFactory;
import com.github.nylle.javafixture.SpecimenType;
import java.lang.annotation.Annotation;
public class ObjectSpecimen<T> implements ISpecimen<T> {
private final SpecimenType<T> type;
private final Context context;
private final SpecimenFactory specimenFactory;
private final InstanceFactory instanceFactory;
public ObjectSpecimen(SpecimenType<T> type, Context context, SpecimenFactory specimenFactory) {
if (type == null) {
throw new IllegalArgumentException("type: null");
}
if (context == null) {
throw new IllegalArgumentException("context: null");
}
if (specimenFactory == null) {
throw new IllegalArgumentException("specimenFactory: null");
}
if (type.isPrimitive() || type.isEnum() || type.isBoxed() || type.asClass() == String.class || type.isMap() || type.isCollection() || type.isInterface()) {
throw new IllegalArgumentException("type: " + type.getName());
}
this.type = type;
this.context = context;
this.specimenFactory = specimenFactory;
this.instanceFactory = new InstanceFactory(specimenFactory);
}
@Override
public T create(CustomizationContext customizationContext, Annotation[] annotations) {
if (context.isCached(type)) {
return context.cached(type);
}
if (customizationContext.useRandomConstructor()) {
return instanceFactory.construct(type, customizationContext);
}
return populate(customizationContext);
}
private T populate(CustomizationContext customizationContext) {
var result = context.cached(type, instanceFactory.instantiate(type));
var reflector = new Reflector<>(result, type).validateCustomization(customizationContext);
try {
reflector.getDeclaredFields()
.filter(field -> !customizationContext.getIgnoredFields().contains(field.getName()))
.forEach(field -> reflector.setField(field,
customizationContext.getCustomFields().getOrDefault(
field.getName(),
specimenFactory
.build(SpecimenType.fromClass(field.getGenericType()))
.create(customizationContext.newForField(field.getName()), reflector.getFieldAnnotations(field)))));
} catch (SpecimenException ex) {
context.overwrite(type, instanceFactory.construct(type, customizationContext));
}
return context.remove(type);
}
}