我使用Toothpick DI进行了检测 Android 测试:
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
private static final String LOG_TAG = ExampleInstrumentedTest.class.getName();
@Inject
Context mContext;
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertThat(appContext.getPackageName(), startsWith("com.honeybeeapp.toothpicktest.mytoothpickapplication"));
final SimpleApp application = (SimpleApp) appContext.getApplicationContext();
Scope scope = Toothpick.openScopes(application, this);
Module module = new Module();
module.bind(Context.class).toInstance(application);
scope.installTestModules(module);
Toothpick.inject(this, scope);
assertTrue(mContext != null); // FAILS :(
Log.d(LOG_TAG, "Injected");
}
}
应用程序的其余部分工作正常,我的 Activity、Services 和 Fragments 上的注入工作正常。
当我Toothpick.inject(otherThing, scope);
在仪器测试中调用不同类的实例时,该注入工作正常。
我的怀疑是 Tests 类(或应用程序?)@Inject
由于某种原因没有正确找到装饰成员。
我试过scope.installModules(module);
了,也不管用。
我的 gradle 文件的一些位:
android {
compileSdkVersion 27
flavorDimensions "default"
defaultConfig {
applicationId "com.honeybeeapp.toothpicktest.mytoothpickapplication"
minSdkVersion 19
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
javaCompileOptions {
annotationProcessorOptions {
arguments = [
'toothpick_registry_package_name': 'com.honeybeeapp.toothpicktest.mytoothpickapplication',
]
}
}
}
snip...
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.android.support:support-v4:27.1.1'
compile 'com.github.stephanenicolas.toothpick:toothpick-runtime:1.1.3'
compile 'com.github.stephanenicolas.toothpick:smoothie:1.1.3'
annotationProcessor 'com.github.stephanenicolas.toothpick:toothpick-compiler:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
testCompile 'com.github.stephanenicolas.toothpick:toothpick-testing:1.1.3'
}
完整的 gradle文件。