问题描述
请在我的 Module 类下面检查,我在其中定义了需要使用 Hilt
NVModule.kt
@Module
@InstallIn(SingletonComponent::class)
class NVModule {
@Provides
@Named("ProfileHelper")
fun abprovideProfileHelper(): ProfileHelper {
return ProfileHelper(AppController.getInstance())
}
}
现在请检查我的接口,我通过它使用 EntryPoint
访问了 Activity/Fragment
之外的依赖注入,例如 Helper
类。
@EntryPoint
@InstallIn(SingletonComponent.class)
public interface CommonHiltInterface {
@Named("ProfileHelper")
public ProfileHelper provideProfileHelper();
}
}
现在请检查我使用了如下依赖注入的 Activity
类,在这里工作正常。意味着正确获得依赖注入
public class HomeActivity extends BaseActivity{
private ActivityHomescreenBinding
activityHomescreenBinding;
private Activity context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
activityHomescreenBinding =
DataBindingUtil.inflate(getLayoutInflater(),R.layout.activity_homescreen,null,false);
setContentView(activityHomescreenBinding.getRoot());
CommonHiltInterface commonHiltInterface = EntryPointAccessors.fromApplication(context,CommonHiltInterface.class);
commonHiltInterface.provideProfileHelper().setData();
}
}
但是在测试用例的情况下,依赖注入得到 NullPointerException 。我在测试用例中使用了 Robolectric。请检查我下面的 RobolectricTest 案例代码行。
@HiltAndroidTest
@RunWith(RobolectricTestRunner.class)
@Config(application = HiltTestApplication.class,sdk = Build.VERSION_CODES.N,manifest = Config.NONE)
public class HomeActivityTest {
@Rule
public HiltAndroidRule hiltRule = new
HiltAndroidRule(this);
@Before
public void setUp() throws Exception {
shadowOf(Looper.getMainLooper()).idle();
hiltRule.inject();
activity =
Robolectric.buildActivity(HomeActivity.class).
create().resume().get();
}
}
注意 :- 1).我也将 @HiltAndroidApp()
用于应用程序类。并使用 2.36 版本进行刀柄依赖
2)。我的依赖注入适用于 Activity/Fagment 和 Helper 类等 Java 类,但不适用于测试用例。
请检查我对 Hilt 的依赖如下
testImplementation 'com.google.dagger:hilt-android-testing:2.36'
kaptTest 'com.google.dagger:hilt-android-compiler:2.36'
testAnnotationProcessor 'com.google.dagger:hilt-android-compiler:2.36'
androidTestImplementation 'com.google.dagger:hilt-android-testing:2.36'
kaptAndroidTest 'com.google.dagger:hilt-android-compiler:2.36'
应用程序运行成功,但在测试用例的情况下,我在 Activity (HomeActivity) 的代码行下方收到空指针异常。
CommonHiltInterface commonHiltInterface = EntryPointAccessors.fromApplication(context,CommonHiltInterface.class);
commonHiltInterface.provideProfileHelper().setData();
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)