Dagger 2-在活动中插入字段

问题描述 投票:0回答:1

[开始之前,我已经阅读了很多教程,但是每个教程都包含有关旧匕首的信息-使用@builder,现在已弃用。我正在使用@Factory

我有什么?

class LoginActivity : AppCompatActivity() {

@Inject
lateinit var authService: AuthService

override fun onCreate(savedInstanceState: Bundle?) {
    AndroidInjection.inject(this)
....
}
}
//----------------
@Singleton
@Component(modules = [TestAppModule::class])
interface TestApplicationComponent : AndroidInjector<TestMyApplication> {
    @Component.Factory
    abstract class Builder : AndroidInjector.Factory<TestMyApplication>
}
//----------------
class TestMyApplication : MyApplication() {
    override fun onCreate() {
        super.onCreate()
        JodaTimeAndroid.init(this)
    }
    override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerTestApplicationComponent.factory().create(this)
    }
}
//----------------
@Singleton
open class AuthService @Inject constructor(
    @AppContext val context: Context, private val authRemoteDataSource: AuthRemoteDataSource
) {
...
}
//----------------
class MockRunner : AndroidJUnitRunner() {
    override fun onCreate(arguments: Bundle?) {
        StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().permitAll().build())
        super.onCreate(arguments)
    }

    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
        return super.newApplication(cl, TestMyApplication::class.qualifiedName, context)
    }
}

[Notes

  1. 我向您展示,AuthService中的构造方法,因为它有多个0参数
  2. 模拟赛跑者申请了我的TestMyApplication课程

和TestClass

@RunWith(AndroidJUnit4::class)
    class LoginActivityTest {

@Mock
lateinit var mockAuthService: AuthService

@Rule
@JvmField
val activityRule = ActivityTestRule<LoginActivity>(LoginActivity::class.java, false, false)

@Before
fun beforeEach() {
    MockitoAnnotations.initMocks(this)
    Mockito.doReturn(NOT_SIGNED).`when`(mockAuthService).getUserSignedStatus(ArgumentMatchers.anyBoolean())
    println(mockAuthService.getUserSignedStatus(true)) //test
}

@Test
fun buttonLogin() {
    activityRule.launchActivity(Intent())
    onView(withText("Google")).check(matches(isDisplayed()));
}
}

我想要什么?-以最简单的方式将模拟的AuthService附加到LoginActivity

我有什么?错误:

[同时调用方法:android.content.Context.getSharedPreferences符合以下条件:

Mockito.doReturn(NOT_SIGNED).`when`(mockAuthService).getUserSignedStatus(ArgumentMatchers.anyBoolean())

方法getSharedPreferences在实际方法getUserSignedStatus中被调用。 所以现在,由于Mockito.when调用了公共的实函数,因此出现错误。我认为,第二个问题将是模拟的AuthService没有注入到LoginActivity

android dependency-injection mockito junit4 dagger-2
1个回答
0
投票

因此您可能应该通过一个模块提供AuthService,一个用于普通应用程序,一个用于android测试,后者提供了模拟版本。那将意味着从AuthService类中删除Dagger注释。我不使用Component.Factory,但此示例足以供您参考。

androidTest文件夹中:

创建测试模块:

// normal app should include the module to supply this dependency
@Module object AndroidTestModule {

    @Provides
    @Singleton
    @JvmStatic
    fun mockService() : AuthService {
        val mock = Mockito.mock(AuthService::class.java
        Mockito.doReturn(NOT_SIGNED).`when`(mockAuthService).getUserSignedStatus(ArgumentMatchers.anyBoolean())
        return mock
    }
}

创建测试组件:

@Component(modules = [AndroidTestModule::class])
@Singleton
interface AndroidTestComponent : AndroidInjector<AndroidTestApp> {

    @Component.Builder interface Builder {

        @BindsInstance fun app(app : Application) : Builder

        fun build() : AndroidTestComponent
    }
}

创建测试应用程序:

class AndroidTestApp : DaggerApplication() {

    override fun onCreate() {
        super.onCreate()

        Timber.plant(Timber.DebugTree())
    }

    override fun applicationInjector(): AndroidInjector<out DaggerApplication> =
            DaggerAndroidTestAppComponent.builder().app(this).build()
}

然后是跑步者:

class AndroidTestAppJunitRunner : AndroidJUnitRunner() {

    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
        return super.newApplication(cl, AndroidTestApp::class.java.canonicalName, context)
    }
}

包含在Gradle的android闭包中:

testInstrumentationRunner "com.package.name.AndroidTestAppJunitRunner"

添加这些部门:

kaptAndroidTest "com.google.dagger:dagger-compiler:$daggerVersion"
kaptAndroidTest "com.google.dagger:dagger-android-processor:$daggerVersion"

androidTestImplementation "org.mockito:mockito-android:2.27.0"
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

然后测试:

@RunWith(AndroidJUnit4::class) class LoginActivityTest {

    @Rule
    @JvmField
    val activityRule = ActivityTestRule<LoginActivity>(LoginActivity::class.java, false, false)

    @Before
    fun beforeEach() {
    }

    @Test
    fun buttonLogin() {
        activityRule.launchActivity(Intent())
        onView(withText("Google")).check(matches(isDisplayed()));
    }
}

您的依赖性将通过生成的测试组件图提供给LoginActivity

© www.soinside.com 2019 - 2024. All rights reserved.