我只是想检查用户是否使用异步方法创建,我是测试新手,所以我正在使用ArgumentCaptor
检查onRegistrationSucces()
回调是否被调用过1次检查它是否成功。
这就是我所做的测试
@Test
fun should_SignUpUser(){
presenter.signUp("test1","test1@gmail.com","asdasd")
verify(interactor).createUserWithEmailAndPassword("test1","test1@gmail.com","asdasd",object: RegisterInteractor.RegisterCallBack{
override fun onRegistrationSucces() {
callbackCaptor.capture()
}
override fun onRegistrationFailure(errorMsg: String) {
callbackCaptor.capture()
}
})
verify(callbackCaptor.value.onRegistrationSucces(), times(1))
}
这是我要测试的演示者方法
override fun signUp(fullName:String, email: String, password: String) {
view?.showProgress()
registerInteractor.createUserWithEmailAndPassword(fullName,email, password, object : RegisterInteractor.RegisterCallBack {
override fun onRegistrationSucces() {
if(isViewAttached()){
view?.navigateToLogin()
view?.hideProgress()
}
}
override fun onRegistrationFailure(errorMsg:String) {
if(isViewAttached()){
view?.showError(errorMsg)
view?.hideProgress()
}
}
})
}
但是我遇到了这个错误
参数不同!通缉: interactor.createUserWithEmailAndPassword( “ test1”, “ test1@gmail.com”, “ asdasd”, com.testapp.presentation.register.presenter.RegisterPresenterTest$should_SignUpUser$1@c86b9e3 ); -> com.testapp.presentation.register.presenter.RegisterPresenterTest.should_SignUpUser(RegisterPresenterTest.kt:119) 实际调用具有不同的参数: interactor.createUserWithEmailAndPassword( “ test1”, “ test1@gmail.com”, “ asdasd”, com.testapp.presentation.register.presenter.RegisterPresenter$signUp$1@10aa41f2 ); -> com.testapp.presentation.register.presenter.RegisterPresenter.signUp(RegisterPresenter.kt:64)
答案 0 :(得分:2)
inner class below:
class CallbackRegister extends RegisterInteractor.RegisterCallBack {
private View view;
private Object forViewattached;
public CallbackRegister(Object forViewattached, View view){
this.forViewattached=forViewattached;
this.view = view;
}
override fun onRegistrationSucces() {
if(forViewattached.isViewAttached()){
view?.navigateToLogin()
view?.hideProgress()
}
}
override fun onRegistrationFailure(errorMsg:String) {
if(forViewattached.isViewAttached()){
view?.showError(errorMsg)
view?.hideProgress()
}
}
//end class
}
Access this by the kotlin equivalent:
object : new CallbackRegister(forViewattached, view)
instead of object: RegisterInteractor.RegisterCallBack{...}
you can easily test this by: TopLevelClass.CallbackRegister callbackRegisterUnderTest = new TopLevelClass().new CallbackRegister(MockforViewattached, MockView);
You can now call the callback methods directly and verify the mocks:
callbackRegisterUnderTest.onRegistrationSucces()
verify the mocks did something.
You have to convert this to kotlin, but I hope you see what is happening.
答案 1 :(得分:0)
问题在于,每个createuserwithemailandpasswords方法的回调都不同。这就是为什么您看到“参数不同”错误的原因。
使用以下命令正确捕获回调:
verify(interactor).createUserWithEmailAndPassword(anyString(),anyString(),anyString(),callbackCaptor.capture())
verify(callbackCaptor.value.onRegistrationSucces(), times(1))
如果您要验证字符串,可以用唯一的字符串捕获器替换anyString。