Is my unit test code is correct?
LoginFragmentViewModel.java
private final LoginRepository mLoginRepository;
MutableLiveData<String> mLoginResponseLiveData;
public LoginFragmentViewModel() {
mLoginRepository = new LoginRepository();
}
public LiveData<String> doLogin(String username, String password) {
mLoginResponseLiveData = mLoginRepository.login(username, password);
return mLoginResponseLiveData;
}
LoginFragmentViewModelTest.java
@Test
public void check_do_login(){
LoginRepository loginRepository = mock(LoginRepository.class);
MutableLiveData<String> mutableLiveData = mock(MutableLiveData.class);
mutableLiveData.setValue("Testing value");
when(loginRepository.login(anyString(), anyString())).thenReturn(mutableLiveData);
LiveData<String> stringLiveData = mLoginFragmentViewModel.doLogin("username@gmail.com", "password@123");
assertEquals(stringLiveData.getValue(),"Testing value");
}
You are getting mocking wrong :
MutableLiveData<String> mutableLiveData = mock(MutableLiveData.class);
mutableLiveData.setValue("Testing value");
That first line creates a mock object. This object has nothing to do with the real implementation. Therefore your second call is pointless !
You need a mock specification instead; like for the other mock:
when(mutableLiveData.getValue()).thenReturn("Testing value");
But the question is: are you sure that you have to create a mocked instance of MutableLiveData?
You see - even when you fix that problem I outlined - your test is doing nothing else but "re-implementing" the production code. Yes, the test tests that production code, but as soon as you change your production code, chances are that your test will break.
Long story short:
mutableLiveData
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.