Flutter Engine
The Flutter Engine
FlutterEngineRule.java
Go to the documentation of this file.
1package io.flutter.embedding.engine.renderer;
2
3import static org.mockito.Mockito.mock;
4import static org.mockito.Mockito.when;
5
6import android.content.Context;
7import android.content.Intent;
8import androidx.test.core.app.ApplicationProvider;
9import io.flutter.embedding.android.FlutterActivity;
10import io.flutter.embedding.engine.FlutterEngine;
11import io.flutter.embedding.engine.FlutterEngineCache;
12import io.flutter.embedding.engine.FlutterJNI;
13import io.flutter.embedding.engine.loader.FlutterLoader;
14import org.junit.rules.TestWatcher;
15import org.junit.runner.Description;
16
17/**
18 * Prepares and returns a {@link FlutterEngine} and {@link Intent} primed with an engine for tests.
19 */
20public final class FlutterEngineRule extends TestWatcher {
21 private static final String cachedEngineId = "flutter_engine_rule_cached_engine";
22 private final Context ctx = ApplicationProvider.getApplicationContext();
23 private FlutterJNI flutterJNI;
24 private FlutterEngine flutterEngine;
25 private boolean jniIsAttached = true;
26
27 @Override
28 protected void starting(Description description) {
29 // Setup mock JNI.
30 flutterJNI = mock(FlutterJNI.class);
31 when(flutterJNI.isAttached()).thenAnswer(i -> jniIsAttached);
32
33 // We will not try to load plugins in these tests.
34 FlutterLoader mockFlutterLoader = mock(FlutterLoader.class);
35 when(mockFlutterLoader.automaticallyRegisterPlugins()).thenReturn(false);
36
37 // Create an engine.
38 flutterEngine = new FlutterEngine(ctx, mockFlutterLoader, flutterJNI);
39
40 // Place it in the engine cache.
41 FlutterEngineCache.getInstance().put(cachedEngineId, flutterEngine);
42 }
43
44 @Override
45 protected void finished(Description description) {
47 }
48
49 /**
50 * Returns a Mockito-mocked version of {@link FlutterJNI}.
51 *
52 * @return an instance that is already considered attached.
53 */
55 return this.flutterJNI;
56 }
57
58 /**
59 * Returns a pre-configured engine.
60 *
61 * @return flutter engine using the mock provided by {{@link #getFlutterJNI()}}.
62 */
64 return this.flutterEngine;
65 }
66
67 /**
68 * Sets what {@link FlutterJNI#isAttached()} returns. If not invoked, defaults to true.
69 *
70 * @param isAttached whether to consider JNI attached.
71 */
72 void setJniIsAttached(boolean isAttached) {
73 this.jniIsAttached = isAttached;
74 }
75
76 /**
77 * Creates an intent with {@link FlutterEngine} instance already provided.
78 *
79 * @return intent, i.e. to use with {@link androidx.test.ext.junit.rules.ActivityScenarioRule}.
80 */
81 Intent makeIntent() {
82 return FlutterActivity.withCachedEngine(cachedEngineId).build(ctx);
83 }
84}
static CachedEngineIntentBuilder withCachedEngine(@NonNull String cachedEngineId)
void put(@NonNull String engineId, @Nullable FlutterEngine engine)