首页 > 解决方案 > 单元测试中的调用目标异常

问题描述

我是单元测试的新手。请让我了解错误在哪里。

FirebaeAuthRespository.java

    public MutableLiveData<IBDataWrapper<User>> signInWithEmailPassword(FirebaseAuth firebaseAuth, String email, String password){

    MutableLiveData<IBDataWrapper<User>> authenticatedUserMutableLiveData = new MutableLiveData<>();
    firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {

            if(task.isSuccessful()){
                FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
                if (firebaseUser != null) {
                  

              authenticatedUserMutableLiveData.setValue(IBDataWrapper.success(firebaseUser, null));
                }
            }else{
                authenticatedUserMutableLiveData.setValue(IBDataWrapper.error(task.getException().getMessage() , null , null));
            }
        }
    });
   return authenticatedUserMutableLiveData;
}

视图模型

public class LoginViewModel extends AndroidViewModel {

MutableLiveData<IBDataWrapper<User>> authenticatedUserMutableLiveData;
private IBFirebaseAuthRepository mIBFirebaseAuthRepository;

public MutableLiveData<IBDataWrapper<User>> ibAuthenticatedUserLiveData;
FirebaseAuth mFirebaseAuth;

public LoginViewModel(Application application) {
    super(application);
    mIBFirebaseAuthRepository = new IBFirebaseAuthRepository();
}

public LoginViewModel(Application application,FirebaseAuth firebaseAuth) {
    super(application);

    mFirebaseAuth = firebaseAuth;
    mIBFirebaseAuthRepository = new IBFirebaseAuthRepository();
}

public void authenticateUser(String email, String password){
   mFirebaseAuth = FirebaseAuth.getInstance();
    ibAuthenticatedUserLiveData = mIBFirebaseAuthRepository.signInWithEmailPassword(mFirebaseAuth , email, password);
}


}

登录活动.java

   private void initLoginViewModel(){
    mLoginViewModel =  new ViewModelProvider(this).get(LoginViewModel.class);
}
 private void signInWithEmailPassword(String email, String password)
{
    // Input fields validation
    if(email.isEmpty() || password.isEmpty()){
        showSnackBar("Please enter your credentials");
        return;
    }

    // Network Connectivity check
    if(!new IBNetworkCheck(this).isNetworkAvailable()){
        showErrorDialog(0,Common.ERROR_TITLE_NETWORK , Common.ERROR_MSG_NETWORK);
        return;
    }

    ProgressBarHandler pbHandler = new ProgressBarHandler(this);
    pbHandler.show();
    mLoginViewModel.authenticateUser(email, password);
    mLoginViewModel.ibAuthenticatedUserLiveData.observe(this, userIBDataWrapper -> {

        pbHandler.hide();
        User user =  userIBDataWrapper.data;
        if(user != null){

            // Get USer profile
            mLoginViewModel.getUserProfile(user.getUserId());
            mLoginViewModel.ibUserProfileLiveData.observe(this, userProfileDataWrapper ->{

                if(userProfileDataWrapper.boolSatuts == IBDataWrapper.BoolStatus.TRUE){
                    User userWithProfile = userProfileDataWrapper.data;
                    if(userWithProfile != null){

                        Common.currentUser = userWithProfile;
                        goToHomeActivity();
                        finish();
                    }
                    else{
                        IBLogger.logErrorMessage("IntiBhojanam" , "[Error Occurred 1] - Retrieving User Profile");
                    }

                }
                else{
                    IBLogger.logErrorMessage("IntiBhojanam" , "[Error Occurred 2] - Retrieving User Profile");
                }
            });
        }
        else{
            IBLogger.logErrorMessage("Test"," Login Failed");
            String msg = userIBDataWrapper.message;
            if(Objects.requireNonNull(msg).contains("network error")){
                showErrorDialog(0,Common.ERROR_TITLE_NETWORK , Common.ERROR_MSG_NETWORK);
            }
            else if(msg.contains("no user record")){
                showErrorDialog(0,"Error" , "There is no user registered for the entered account information. Please recheck and try again!");
            }
            else{
                showErrorDialog(0,"Error" , msg);
            }
            //showSnackBar(userIBDataWrapper.message);
        }
    });
}

LoginViewModelTest.java

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(JUnit4.class)
@PrepareForTest({ FirebaseDatabase.class})
public class LoginViewModelTest {

private DatabaseReference mockedDatabaseReference;
private FirebaseAuth mockAuth;

private LoginViewModel mockLoginViewModel;

@Before
public void before() {
    mockedDatabaseReference = Mockito.mock(DatabaseReference.class);

    mockAuth = mock(FirebaseAuth.getInstance().getClass());
    mockLoginViewModel = mock(LoginViewModel.class);

    FirebaseDatabase mockedFirebaseDatabase = Mockito.mock(FirebaseDatabase.class);
    when(mockedFirebaseDatabase.getReference()).thenReturn(mockedDatabaseReference);

    PowerMockito.mockStatic(FirebaseDatabase.class);
    when(FirebaseDatabase.getInstance()).thenReturn(mockedFirebaseDatabase);
}

@Test
public void test_firebase_auth(){
    mockLoginViewModel.authenticateUser("abc@gmail.com" , "123456");
  //  verify(mockAuth).createUserWithEmailAndPassword("abc@gmail.com" , "123456");

    }
}

我得到这个错误。

org.objenesis.ObjenesisException: java.lang.reflect.InvocationTargetException

调用视图模型测试firebas登录注册功能的错误是什么。请告诉我。提前致谢。

标签: androidfirebase-realtime-databasemvvmpowermockitoandroid-unit-testing

解决方案


推荐阅读