I am unable to test SharedPreference using Mockito - android

I am unable to mock sharedPreference and when i test my presenter then sharepreference instance is null.
#RunWith(MockitoJUnitRunner.class)
public class PreferencesPresenterTest {
#Mock
PreferencesMvpView preferencesMvpView;
#Mock
ApiService apiService;
#Mock
Context context;
#Mock
SchedulerProvider mSchedulerProvider;
PreferencesPresenter mPresenter;
#Before
public void setUp() throws Exception {
CompositeDisposable compositeDisposable = new CompositeDisposable();
mPresenter = new PreferencesPresenter(compositeDisposable, apiService, mSchedulerProvider);
// mPrefences = new AppPreferences();
mPresenter.onAttach(preferencesMvpView);
}
#Test
public void testFilter() throws Exception {
Mockito.when(mSchedulerProvider.getUiScheduler()).thenReturn(Schedulers.trampoline());
Mockito.when(mSchedulerProvider.getWorkerScheduler()).thenReturn(Schedulers.trampoline());
mPresenter.loadPreferenceData();
}
}
//This is the method which i am testing
#Override
public void loadPreferenceData() {
long userId = mPreferences.getLong(AppPreferences.USER_ID);
getMvpView().showLoading();
getCompositeDisposable().add(getApiService().getPreferencesData(userId)
.subscribeOn(getSchedulerProvider().getWorkerScheduler())
.observeOn(getSchedulerProvider().getUiScheduler())
.subscribe(
jsonObject -> {
//Log.d(getClass().getSimpleName(), "PreferencesPresenter : loadPreferenceData: onSuccess");
if (!isViewAttached()) {
return;
}
getMvpView().hideLoading();
if (jsonObject != null && AppUtils.containsValue(jsonObject, JsonKeys.DATA))
setupFieldList(new Gson().fromJson(jsonObject.get(JsonKeys.DATA), Preferences.class));
}
, throwable -> {
// Log.d(getClass().getSimpleName(), "PreferencesPresenter : loadPreferenceData: Error");
if (!isViewAttached()) {
return;
}
getMvpView().hideLoading();
handleApiError(throwable);
}));
}

Are you running unit tests? By default, any calls to the Android framework from within a unit test will throw an exception.
From https://developer.android.com/training/testing/fundamentals#interact-android-environment:
You can control and verify the elements of the Android framework with which your app interacts by running unit tests against a modified version of android.jar, which doesn't contain any code. Because your app's calls to the Android framework throw exceptions by default, you need to stub out every one of these interactions by using a mocking framework, such as Mockito.
You have a few options here:
Encapsulate the code that interacts with SharedPreferences in a separate class and mock out that class with Mockito when testing your Presenter
Use Robolectric, which provides an implementation of the Android SDK
Run instrumented tests (androidTest) instead of unit tests (test)
I would recommend #1, as that approach allows you to continue running fast JUnit tests without having to deal with the overhead of Robolectric.

Related

Why does the view methods does not get called inside an Observable which is inside the presenter on a unit test?

I am new to Android Unit Testing and we are currently using MVP+RxJava+Dagger 2. I wrote this test which fails in unit test, but works in production code:
#Override
public void retrieveListOfBillers() {
getMvpView().showLoading();
getCompositeDisposable().add(
getDataManager()
.doServerGetBillersList()
.observeOn(getSchedulerProvider().ui())
.subscribeOn(getSchedulerProvider().io())
.subscribe( response ->{
for (Datum data : response.getData()) {
getMvpView().setUpRecyclerView(enrollmentBillers);
getMvpView().showDefaultViews();
getMvpView().hideLoading();
}, throwable -> {
...
And this is how I do it in the test:
#Test
public void testGetListOfBillersCallsSetupRecyclerView(){
mPresenter.retrieveListOfBillers();
verify(mView).showLoading();
verify(mView).setUpRecyclerView(anyList());
}
This is how I instanciated the setup for the test:
#Before
public void setUp() {
// Mockito has a very convenient way to inject mocks by using the #Mock annotation. To
// inject the mocks in the test the initMocks method needs to be called.
MockitoAnnotations.initMocks(this);
CompositeDisposable compositeDisposable = new CompositeDisposable();
mTestScheduler = new TestScheduler();
testSchedulerProvider = new TestSchedulerProvider(mTestScheduler);
mPresenter = new CreateBillerContactPresenter<>(
dataManager,
testSchedulerProvider,
compositeDisposable
);
mPresenter.onAttach(mView);
when(dataManager.doServerGetBillersList()).thenReturn(Observable.just(getBillerListResponse));
I believe it has something to do with the TestScheduler but I need someone who actually knows what is the problem here, which is why my test code fails to call setupRecyclerView, and other expected view method calls from the presenter?
I have found the answer:
It seems the TestScheduler class have a triggerAction method in which:
"Triggers any actions that have not yet been triggered and that are scheduled to be triggered at or before this Scheduler's present time." -- from comments above the method.
Then the presenter/datamanager calls the view methods as expected.

Unit test Android, getString from resource

I am trying to do an unit test for an android app and I need to get a string from res.string resources. The class that I want to test is a POJO class. I am doing the app in two languages, due to this, I need to get a string from resource. The problem is that I cannot get the context or the activity, is possible? I know that with Instrumentation test I can do it, but I need to test some functions (white box test) before to do the instrumentation test (black box test).
This is the function that I have to test:
public void setDiaByText(String textView) {
getll_diaSeleccionado().clear();
if (textView.contains(context.getResources().getString(R.string.sInicialLunes))) {
getll_diaSeleccionado().add(0);
getIsSelectedArray()[0] = true;
getI_idiaSeleccionado()[0] =1;
} else
{
getIsSelectedArray()[0] = false;
getI_idiaSeleccionado()[0] =0;
}
}
And this is the test:
#Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
It crash when try to do context.getResources().getString(R.string.sInicialLunes))
If I put 'Mon' instead of context.getResources().getString(R.string.sInicialLunes)) or 'L' it work perfectly so, is possible to get the context or the activity in order to access to resource folder?
I am testing with Mockito and the setUp function is:
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mContext = Mockito.mock(Alerta.class);
Mockito.when(mContext.getApplicationContext()).thenReturn(mContext);
alertaPOJO = new AlertaPOJO();
}
Thanks
If you are using Context only for obtaining String resource, I would go by mocking only getResources().getString() part like this (see JUnit4 notation):
#RunWith(MockitoJUnitRunner.class)
public class AlertaPOJOTest {
#Mock
Context mMockContext;
#Test
public void setDiaByTextView() {
String texto = "L,M,X,J,V,S,D";
when(mMockContext.getString(R.string.sInicialLunes))
.thenReturn(INITIAL_LUNES);
alertaPOJO.setDiaByText(texto);
assertEquals(alertaPOJO.getIsSelectedArray()[0], true);
assertEquals(alertaPOJO.getI_idiaSeleccionado()[0], 1);
}
}
There are many reasons to stay with JVM tests, most important one, they are running quicker.
Untested: would it work to use the below, and probably targetContext?
android {
testOptions {
unitTests {
includeAndroidResources = true
}
}
}
You don't have a real android Context while you are using JVM unit test. For your case, maybe you can try Android Instrumentation Test, typically it is implemented in the "androidTest" directory of your project.
If you use MockK it's the same.
#RunWith(AndroidJUnit4::class)
class YourClassUnitTest : TestCase() {
#MockK
private lateinit var resources: Resources
#Before
public override fun setUp() {
MockKAnnotations.init(this)
}
#Test
fun test() {
every {
resources.getQuantityString(R.plurals.age, YEARS, YEARS)
} returns AGE
every {
resources.getString(
R.string.surname,
SURNAME
)
} returns TITLE
// Assume you test this method that returns data class
// (fields are calculated with getQuantityString and getString)
val data = getData(YEARS, SURNAME)
assertEquals(AGE, data.age)
assertEquals(TITLE, data.title)
}
companion object {
const val YEARS = 10
const val AGE = "$YEARS years"
const val SURNAME = "Johns"
const val TITLE = "Mr. $SURNAME"
}
}
See also Skip a parameter in MockK unit test, Kotlin to get a result of string resources for any data.

UntTest - Mock RxJava object in UseCase Object

I want to test UseCase object, in this specific case there is a LoginUseCase, which looks like this:
public class LoginUseCase implements RxUseCase<AuthResponse, AuthCredentials> {
ApiManager mApiManager;
public LoginUseCase(ApiManager apiManager) {
mApiManager =apiManager;
}
#Override
public Observable<AuthResponse> execute(final AuthCredentials authCredentials) {
return Observable.just(1)
.delay(750, TimeUnit.MILLISECONDS)
.flatMap(l -> mApiManager.login(authCredentials.getLogin(), authCredentials.getPassword()));
}
}
I wrote simple test:
#RunWith(MockitoJUnitRunner.class)
public class LoginUseCaseTest {
private LoginUseCase mLoginUseCase;
#Mock ApiManager mApiManager;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mLoginUseCase = new LoginUseCase(mApiManager);
}
#Test
public void testShouldThrowsError() throws Exception {
TestSubscriber<AuthResponse> testSubscriber = new TestSubscriber<>();
doReturn(Observable.error(new Throwable())).when(mApiManager).login("", "");
mLoginUseCase
.execute(new AuthCredentials("", ""))
.subscribe(testSubscriber);
testSubscriber.assertNoErrors();
}
}
But this test always passes and I don't know how mock error observable in this case.
EDIT: I've chaged testShouldThrowsError() according to SkinnyJ, but test still passes, any sugestions?
You need to call awaitTerminalEvent() on your test subscriber before assertions.
Because now, you schedule a delay to be run on Schedulers.computation and your test method successfully completes before completion of observable.
Alternative approach would be to pass scheduler as argument to execute method, or store scheduler in your usecase. This way, during test you can pass Schedulers.immediate() and your test will run on current thread (which will block execution for specified delay).
And last approach is to call toBlocking() on observable, but I think that passing scheduler is preferred choice. And there is no way to add this operator to your current observable.

Mockito and callback returning "Argument(s) are different!"

I'm trying to use mockito on android. I want to use it with some callback.
Here my test :
public class LoginPresenterTest {
private User mUser = new User();
#Mock
private UsersRepository mUsersRepository;
#Mock
private LoginContract.View mLoginView;
/**
* {#link ArgumentCaptor} is a powerful Mockito API to capture argument values and use them to
* perform further actions or assertions on them.
*/
#Captor
private ArgumentCaptor<LoginUserCallback> mLoadLoginUserCallbackCaptor;
private LoginPresenter mLoginPresenter;
#Before
public void setupNotesPresenter() {
// Mockito has a very convenient way to inject mocks by using the #Mock annotation. To
// inject the mocks in the test the initMocks method needs to be called.
MockitoAnnotations.initMocks(this);
// Get a reference to the class under test
mLoginPresenter = new LoginPresenter(mUsersRepository, mLoginView);
// fixtures
mUser.setFirstName("Von");
mUser.setLastName("Miller");
mUser.setUsername("von.miller#broncos.us");
mUser.setPassword("Broncos50superBowlWinners");
}
#Test
public void onLoginFail_ShowFail() {
// When try to login
mLoginPresenter.login("von.miller#broncos.us", "notGoodPassword");
// Callback is captured and invoked with stubbed user
verify(mUsersRepository).login(eq(new User()), mLoadLoginUserCallbackCaptor.capture());
mLoadLoginUserCallbackCaptor.getValue().onLoginComplete(eq(mUser));
// The login progress is show
verify(mLoginView).showLoginFailed(anyString());
}
But I got this error :
Argument(s) are different! Wanted:
mUsersRepository.login(
ch.example.project.Model.User#a45f686,
<Capturing argument>
);
-> at example.ch.project.Login.LoginPresenterTest.onLoginFail_ShowFail(LoginPresenterTest.java:94)
Actual invocation has different arguments:
mUsersRepository.login(
ch.example.project.Model.User#773bdcae,
ch.example.project.Login.LoginPresenter$1#1844b009
);
Maybe the issue is that the second actual argument is ch.example.project.Login.LoginPresenter$1#1844b009 ?
I followed : https://codelabs.developers.google.com/codelabs/android-testing/#5
Thank you for help =)
Edit
The method I try to test (LoginPresenter):
#Override
public void login(String email, String password) {
mLoginView.showLoginInProgress();
User user = new User();
user.setUsername(email);
user.setPassword(password);
mUsersRepository.login(user, new UsersRepository.LoginUserCallback() {
#Override
public void onLoginComplete(User loggedUser) {
mLoginView.showLoginComplete();
}
#Override
public void onErrorAtAttempt(String message) {
mLoginView.showLoginFailed(message);
}
});
}
eq(new User())
When using eq (or not using matchers at all), Mockito compares arguments using the equals method of the instance passed in. Unless you've defined a flexible equals implementation for your User object, this is very likely to fail.
Consider using isA(User.class), which will simply verify that the object instanceof User, or any() or anyObject() to skip matching the first parameter entirely.
I am using mvp pattern with rxjava 2 and dagger 2, and was stuck on unit testing a presenter using Mockito. The code that gave me the "Argument(s) are different!” Error:
#Mock
ImageService imageService;
#Mock
MetadataResponse metadataResponse;
private String imageId = "123456789";
#Test
public void getImageMetadata() {
when(imageService.getImageMetadata(imageId)).thenReturn(Observable.just(Response.success(metadataResponse)));
presenter.getImageMetaData(imageId);
verify(view).showImageData(new ImageData()));
}
Which throws error messages such as the following:
Argument(s) are different! Wanted: Actual invocation has different
arguments: com.example.model.ImageData#5q3v861
Thanks to the answer from #Jeff Bowman, it worked after I changed this line
verify(view).showImageData(new ImageData()));
with
verify(view).showImageData(isA(ImageData.class));

Using mocked objects

I've just started unit testing on Android with Mockito - how do you get the class that you are testing on to use the mocked class/object instead of the regular class/object?
You can use #InjectMocks for the class you writing the test.
#InjectMocks
private EmployManager manager;
Then you can use #Mock for the class you are mocking. This will be the dependency class.
#Mock
private EmployService service;
Then write a setup method to make things available for your tests.
#Before
public void setup() throws Exception {
manager = new EmployManager();
service = mock(EmployService.class);
manager.setEmployService(service);
MockitoAnnotations.initMocks(this);
}
Then write your test.
#Test
public void testSaveEmploy() throws Exception {
Employ employ = new Employ("u1");
manager.saveEmploy(employ);
// Verify if saveEmploy was invoked on service with given 'Employ'
// object.
verify(service).saveEmploy(employ);
// Verify with Argument Matcher
verify(service).saveEmploy(Mockito.any(Employ.class));
}
By injecting the dependency:
public class ClassUnderTest
private Dependency dependency;
public ClassUnderTest(Dependency dependency) {
this.dependency = dependency;
}
// ...
}
...
Dependency mockDependency = mock(Dependency.class);
ClassUnderTest c = new ClassUnderTest(mockDependency);
You can also use a setter to inject the dependency, or even inject private fields directly using the #Mock and #InjectMocks annotations (read the javadoc for a detailed explanation of how they work).

Categories

Resources