我对android& java的。我正在尝试编写单元测试,以验证使用正确的参数调用Firebase方法&成功召回的具体回调
public class RegistrationViewModel {
private iRegistrationViewCallback viewCallback;
private FirebaseAuth mAuth;
public String email;
public String password;
public RegistrationViewModel(iRegistrationViewCallback view, FirebaseAuth mockAuth) {
viewCallback = view;
mAuth = mockAuth;
}
public void createUser() {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener((Executor) this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
viewCallback.doSomething();
}
});
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
}
我的单元测试如下:
public class RegistrationViewModelUnitTest {
private RegistrationViewModel viewModelUnderTest;
private iRegistrationViewCallback mockView;
private FirebaseAuth mockAuth;
@Before
public void SetUp() {
mockView = mock(iRegistrationViewCallback.class);
mockAuth = mock(FirebaseAuth.getInstance().getClass());
viewModelUnderTest = new RegistrationViewModel(mockView,mockAuth);
}
@Test
public void progressBarIsDismissedWhenRegistrationIsSuccessFul() throws Exception {
String email = "somusername";
String password = "somePassword";
viewModelUnderTest.email = email;
viewModelUnderTest.password = password;
viewModelUnderTest.createUser();
verify(mockAuth).createUserWithEmailAndPassword(email,password);
verify(mockView).doSomething();
}
}
verify(mockView).doSomething();
显然失败了。
验证成功时调用viewCallback.doSomething();
的最佳方法是什么?我应该以某种方式存根onComplete
吗?或者有不同的方式这样做?我曾想过将Firebase代码放在接口后面,但仍然无法弄清楚如何验证回调是否被触发。
我使用Mockito进行嘲弄。
答案 0 :(得分:0)
这似乎更像是一个整合测试场景。
如果您想进行单元测试,我会执行以下操作:
步骤1)
使用回调行为创建一个公共类,而不是使用匿名类:
public class MyOnCompleteListener implements OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
viewCallback.doSomething();
}
});
第2步)
将您的createUser方法更改为:
public void createUser() {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener((Executor) this
, new MyOnCompleteListener<AuthResult>() );
}
第3步)
按如下方式定义测试:
@Test
public void progressBarIsDismissedWhenRegistrationIsSuccessFul() throws Exception {
String email = "somusername";
String password = "somePassword";
viewModelUnderTest.email = email;
viewModelUnderTest.password = password;
Task taskMock = mock(Task.class);
when(mockAuth.createUserWithEmailAndPassword (email, password)).thenReturn(taskMock);
viewModelUnderTest.createUser();
verify(mockAuth, times(1)).createUserWithEmailAndPassword(email,password);
verify(taskMock, times(1)).addOnCompleteListener(any(RegistrationViewModel.class)
, any(MyOnCompleteListener.class));
}
最重要的是,您确认已为createUserWithEmailAndPassword
方法注册了某个回调。
如果您希望将此作为单元测试而不实际调用框架代码,那么您可以做的就是。