-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
AndroidObjectFactory.java
76 lines (66 loc) · 2.67 KB
/
AndroidObjectFactory.java
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
package cucumber.runtime.android;
import android.app.Instrumentation;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.test.AndroidTestCase;
import android.test.InstrumentationTestCase;
import cucumber.api.java.ObjectFactory;
/**
* Android specific implementation of {@link ObjectFactory} which will
* make sure that created test classes have all necessary references to the executing {@link android.app.Instrumentation}
* and the associated {@link android.content.Context}.
*/
@SuppressWarnings("deprecation")
final class AndroidObjectFactory implements ObjectFactory {
/**
* The actual {@link ObjectFactory} responsible for creating instances.
*/
private final ObjectFactory delegate;
/**
* The instrumentation to set to the objects.
*/
private final Instrumentation instrumentation;
/**
* Creates a new instance using the given delegate {@link ObjectFactory} to
* forward all calls to and using the given {@link android.app.Instrumentation} to set to the instantiated
* android test classes.
*
* @param delegate the {@link ObjectFactory} to delegate to
* @param instrumentation the {@link android.app.Instrumentation} to set to the tests
*/
AndroidObjectFactory(final ObjectFactory delegate, final Instrumentation instrumentation) {
this.delegate = delegate;
this.instrumentation = instrumentation;
}
@Override
public void start() {
delegate.start();
}
@Override
public void stop() {
delegate.stop();
}
@Override
public boolean addClass(final Class<?> clazz) {
return delegate.addClass(clazz);
}
@Override
public <T> T getInstance(final Class<T> type) {
T instance = delegate.getInstance(type);
decorate(instance);
return instance;
}
private void decorate(final Object instance) {
if (instance instanceof ActivityInstrumentationTestCase2) {
final ActivityInstrumentationTestCase2 activityInstrumentationTestCase2 = (ActivityInstrumentationTestCase2) instance;
activityInstrumentationTestCase2.injectInstrumentation(instrumentation);
final Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activityInstrumentationTestCase2.setActivityIntent(intent);
} else if (instance instanceof InstrumentationTestCase) {
((InstrumentationTestCase) instance).injectInstrumentation(instrumentation);
} else if (instance instanceof AndroidTestCase) {
((AndroidTestCase) instance).setContext(instrumentation.getTargetContext());
}
}
}