问题
I have an object in kotlin that controls the current user's session information. I want to mock the sign in method which has a call back.
While testing, I need to mock this method in the SessionController object.
object SessionController {
...
fun signIn(username: String, password: String, signInCallBack: SignInCallBack) {
sessionApi.attemptSignIn(username,password,object: SignInCallBack{
override fun onSignInComplete() {
signInCallBack.onSignInComplete()
}
override fun onErrorOccurred(errorCode: Int, errorMessage: String) {
signInCallBack.onErrorOccurred(errorCode)
}
})
}
....
}
The AndroidTest goes something like this:
@RunWith(AndroidJUnit4::class)
class LoginActivityTest {
@Test
fun loginErrorShowing() {
test.tapUsernameField()
test.inputTextinUsernameField("wrongusername")
test.pressUsernameFieldIMEAction()
test.inputTextinPasswordField("randomPassword")
test.pressPasswordFieldIMEAction()
Espresso.onView(ViewMatchers.withId(R.id.errorText)).check(ViewAssertions.matches(withText("Wrong Password")))
}
}
Any suggestions/ideas as to how I can achieve this? I've read online to use Mockk for kotlin but have't been able to mock this method and invoke the appropriate callback. Any suggestions on improving the structure would also be appreciated.
Thanks
回答1:
Well in my opinion you should made SessionController implementing an interface.
object SessionController: ISessionController {
override fun signIn(username: String, password: String, signInCallBack: SignInCallBack) {
(...)
}
}
interface ISessionController {
fun fun signIn(username: String, password: String, signInCallBack: SignInCallBack)
}
This will give you a lot of possibilities to solve your problem like:
- Dependency Injection
- Test product flavour
- Simple mockk() cration in your test code
It is a bit hard to give you very strict answer because you didn't post any UT code ;)
EDIT
It is hard to cover such a big topic as mocking in one post ;) Here are some great articles:
- Dependency Injection: https://medium.com/@elye.project/fast-mocked-ui-tests-on-android-kotlin-89ed0a8a351a
- Using different flavour for tests: https://android-developers.googleblog.com/2015/12/leveraging-product-flavors-in-android.html
Creating Unit Tests you can always do simple:
presenter.sth = mockk<ISessionController>()
来源:https://stackoverflow.com/questions/49126220/how-to-mock-kotlin-object-in-android