0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Dagger2を使ったアプリでfragment-testingを使ってみたら"No injector was found..." エラー

Last updated at Posted at 2019-04-03

はじめに

AndroidX TestでJVM上でEspressoのテストが実行可能になり、さらにfragment-testing を使えば以下のように簡単にFragment単体でのUIテストを実行できます。

@Test
fun test() {
    launchFragmentInContainer<FooFragment>()
    ...
    onView(...).check(...)
}

しかし、Dagger2を使った既存のアプリで fragment-testing を試してみたところ、以下のようなエラーが発生しました。

java.lang.IllegalArgumentException: No injector was found for FooFragment

Injectorが見つからないとのこと。。。

原因

launchFragmentInContainer() の内部実装を見てみるとテスト用の空Activityである EmptyFragmentActivityにテスト対象のFragmentをattachしていることがわかります。
そしてEmptyFragmentActivity は単純なFragmentActivityを継承したクラスで、Dagger2のHasSupportFragmentInjector は実装していません。
私の試した環境ではHasSupportFragmentInjector未実装ActivityにattachされたFragmentのFragment#onAttach() 内で AndroidSupportInjection#inject(fragment)を呼び出してしまったことが原因で上記エラーが発生してしまいました。

対処法

launchFragmentInContainer() では起動するActivityを任意のものに差し替えることは(今のところ)できません。
https://issuetracker.google.com/issues/121347222

ではどうするか。。。

ApplicationクラスでHasSupportFragmentInjector を実装しましょう!
Applicationクラスで実装しておけばActivityクラスでHasSupportFragmentInjector を実装する必要はありません。


class TestApp: DaggerApplication(), HasSupportFragmentInjector {
    @Inject
    lateinit var supportFragmentInjector: DispatchingAndroidInjector<Fragment>

    override fun supportFragmentInjector(): DispatchingAndroidInjector<Fragment> = 
        supportFragmentInjector

    ...
}

これでlaunchFragmentInContainer() でFragmentを起動可能になり、無事にテスト実行可能になります :sparkles:

サンプルコード

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?