I have a Java EE web application that heavily relies on dependency injection.
Currently it works as expected and it is injecting everything the way I want it to in production and I can without too much hassle inject mock objects when I am writing unit tests.
However I now want to create integration tests so that I know that the entire flow is working and it is getting and parsing correct data from other APIs.
The problem I am seeing now is with solving dependency injection in a test environment, because it is an integration test there are a lot more dependencies to solve, So doing this manually does not seem feasible.
So, How is this usually solved? for reference I am using a mix of @EJB
and @Inject
to inject Objects
.
答案 0 :(得分:0)
我将使用的一个肮脏的黑客解决方法,直到我弄清楚它应该如何完成:
private static Map<Class, Object> instances = new HashMap<>();
public static <T> T getInstance(Class<T> type) throws IllegalAccessException, InstantiationException {
if(instances.containsKey(type))
return (T)instances.get(type);
T res = type.newInstance();
instances.put(type, res);
for(Field field : type.getDeclaredFields()) {
if (field.isAnnotationPresent(Inject.class) || field.isAnnotationPresent(EJB.class)) {
field.setAccessible(true);
field.set(res, getInstance(field.getType()));
}
}
return res;
}