我使用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类(或app?)由于某种原因没有正确找到装饰的@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'
}
完全gra gra file。
答案 0 :(得分:0)
查看similar problem in dagger2我看到他们只需要明确地为测试添加注释处理器。为Toothpick做同样的事情似乎也有效!
在我的gradle file中添加了以下内容:
dependencies {
...
androidTestAnnotationProcessor 'com.github.stephanenicolas.toothpick:toothpick-compiler:1.1.3'
...
}
解决问题,我的测试通过了!