【发布时间】:2020-05-29 16:57:30
【问题描述】:
在开始之前,我已经阅读了很多教程,但每个教程都包含有关旧匕首的信息 - 使用现在已弃用的 @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)
}
}
注意事项:
- 我告诉你,AuthService 中的构造函数,因为它有超过 0 个参数
- 模拟跑步者应用我的
TestMyApplication类
和测试类
@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
【问题讨论】:
-
@sonnet 确实有用的链接,但我再问你一个,如果我创建
@Binds abstract fun provideFakeAuth(fake: LoginActivityTest.FakeAuthService): AuthService,有没有一种简单的方法可以在其他测试中使用其他FakeAuthService?或者我应该从头开始创建整个模块? -
如果我在这里提供模拟并在接下来的测试中更改方法的返回,也许最好的办法是,但是如何? -> 如何提供 mock 并在测试中获取它?
标签: android dependency-injection mockito junit4 dagger-2