I'm using Mockito framework to test a class that returns an Observable (see comments):
This is the my implementation class:
public class DataRepository implements AbstractRepository {
private DataSource dataSource;
private DataMapper dataMapper;
// Constructor
public DataRepository(DataSource dataSource, DataMapper dataMapper) {
this.dataSource = dataSource;
this.dataMapper = dataMapper;
}
/**
* The call to dataSource.getItem(int) returns
* an Observable of type ItemResponse.
* So, in the map I cast it to an object of type Item.
**/
public Observable<Item> getItem(int id) {
return dataSource.getItem(id)
.map(new Function<ItemResponse, Item>() {
#Override
public Item apply(ItemResponse itemResponse) throws Exception {
return dataMapper.transform(itemResponse);
}
});
}
}
Now, this is my test class:
#RunWith(MockitoJUnitRunner.class)
public class DataRepositoryTest {
DataRepository dataRepository;
#Mock
DataSource dataSource;
#Mock
DataMapper dataMapper;
#Before
public void setUp() {
dataRepository = new DataRepository(dataSource, dataMapper);
}
#Test
public void testGetItem() {
// Given
ItemResponse itemResponse = new ItemResponse();
given(dataSource.getItem(anyInt())).willReturn(Observable.just(itemResponse));
// When
dataRepository.getItem(anyInt());
// Verify/then
verify(dataSource).getItem(anyInt()); // This part runs fine.
verify(dataMapper).transform(); // This is failing
}
}
The error message I'm getting is:
Wanted but not invoked:
dataMapper.transform(
com.my.package.ItemResponse#e720b71
);
-> at com.my.package.test.DataRepositoryTest.testGetItem(DataRepositoryTest.java:28)
Actually, there were zero interactions with this mock.
How can I tell Mockito to call the map() operator/method, then apply() of the Observable returned by dataSource.getItem(int)?
Looks like you are not subscribing the Observable<Item> returned by public Observable<Item> getItem(int id) so the .map(...) operator is not being called/executed, try with dataRepository.getItem(anyInt()).subscribe(); just to verify.
Related
In my app, I have a ViewModel looks like that:
public class MyExampleViewModel {
private LiveData<MyEntity> myLiveData;
#Inject
MyRepository myRepository;
#Inject
public MyExampleViewModel() {
}
public void init(final Long id) {
if (this.myLiveData == null) {
this.myLiveData = myRepository.getById(id);
}
}
public void toggleStar() NullPointerException {
final MyEntity myValue = this.myLiveData.getValue();
myValue.setStar(!myValue.getStar());
myRepository.save(myValue);
}
}
Also the code of MyRepository#getById (myDao is a room DAO and it is injected):
public LiveData<MyEntity> getById(final Long id) {
return myDao.getById(id);
}
The code of MyDao#getById:
#Query(
"SELECT * FROM myTable WHERE id=:id"
)
LiveData<MyEntity> getById(final Long id);
I also try to test this ViewModel using
myExampleViewModel.init(myId);
myExampleViewModel.toggleStar();
but after the init call my LiveData value is always null.
My first question is: is it a best practice to use getValue() on my LiveData or should I use Transformation.map?
My second question is: in my test, how can I have a LiveData populated? I tried to use CountingTaskExecutorRule and InstantTaskExecutorRule but without any success.
Thank you for your help!
I understood why myLiveData is not populated in my test. According to the documentation "LiveData objects that are lazily calculated on demand." and LiveData#getValue only get the value if the LiveData is already populated but doesn't calculate the value.
So I fixed my test adding a getter on my LiveData and an observer on my LiveData to force the calculation like that LiveDataUtil.getValue(myExampleViewModel.getMyLiveData()); with LiveDataUtil#getValue:
public class LiveDataUtil {
public static <T> T getValue(final LiveData<T> liveData) throws InterruptedException {
final Object[] data = new Object[1];
final CountDownLatch latch = new CountDownLatch(1);
Observer<T> observer = new Observer<T>() {
#Override
public void onChanged(#Nullable T o) {
data[0] = o;
latch.countDown();
liveData.removeObserver(this);
}
};
new Handler(Looper.getMainLooper()).post(() -> liveData.observeForever(observer));
latch.await(2, TimeUnit.SECONDS);
//noinspection unchecked
return (T) data[0];
}
}
After this fix, MyExampleViewModel class looks like:
public class MyExampleViewModel {
private LiveData<MyEntity> myLiveData;
#Inject
MyRepository myRepository;
#Inject
public MyExampleViewModel() {
}
public void init(final Long id) {
if (this.myLiveData == null) {
this.myLiveData = myRepository.getById(id);
}
}
public void toggleStar() NullPointerException {
final MyEntity myValue = this.myLiveData.getValue();
myValue.setStar(!myValue.getStar());
myRepository.save(myValue);
}
public LiveData<MyEntity> getMyLiveData() {
return myLiveData;
}
}
And my test method:
myExampleViewModel.init(myId);
LiveDataUtil.getValue(myExampleViewModel.getMyLiveData());
myExampleViewModel.toggleStar();
I fixed my test but I still don't know if using LiveData.getValue is a best practice and I found few documentation on this topic. So, I'm interested in this topic if you have more information.
I'm trying to write unit testing for the following snippet.
class ABC {
int getMyValue(final Activity activity) {
if(MyClass.getInstance(activity).getValue() == 1) return 10;
else return 20;
}
void doSomething() {
}
}
I've tried something like this to test the doSomething function.
mABC = new ABC();
public void test_doSomething() {
doReturn(20).when(mABC).getMyValue();
//validate
}
How can I test getMyValue similarly? I would like to assert when the value is 1 it's returning me 10 and in all other cases, it's returning me 20.
I'm doing this in my android application. Is there any existing framework that can help me do this?
EDIT:
MyClass looks something like this
public class MyClass {
private static Context mContext;
public static getInstance(Context context) {
mContext = context;
return new MyClass();
}
private MyClass() {}
public void getDreamValue() {
Settings.Secure.getInt(mContext.getContentResolver(), "dream_val", -1);
}
}
You might consider modifying your MyClass as follows.
public class MyClass {
private static Context mContext;
// Create a private variable that holds the instance.
private Myclass instance;
public static getInstance(Context context) {
mContext = context;
if (instance == null)
instance = new MyClass(); // Assign the instance here
return instance;
}
private MyClass() {}
public void getDreamValue() {
Settings.Secure.getInt(mContext.getContentResolver(), "dream_val", -1);
}
}
Now, as you are using Robolectric, you can set the instance value to a mock as follows in your test class.
#RunWith(RobolectricTestRunner.class)
public class ABCTest {
#Mock
MyClass mockInstance;
#Mock
Context mockContext;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
// Set the mock instance for MyClass
ReflectionHelpers.setStaticField(MyClass.class, "instance", mockInstance);
}
#Test
public void testWhen1() {
doReturn(1).when(mockInstance).getDreamValue();
Assert.assertEquals(10, new ABC().getMyValue());
}
#Test
public void testWhenNot1() {
doReturn(2).when(mockInstance).getDreamValue();
Assert.assertEquals(20, new ABC().getMyValue());
}
#After
public void tearDown() {
// Set the instance to null again to enable further tests to run
ReflectionHelpers.setStaticField(MyClass.class, "instance", null);
}
}
I hope that helps.
Note: It looks like you are trying to provide a singleton instance of MyClass. Hence, you really should not create a new instance of MyClass in the getInstance function. I avoided creating a new instance each time, using the null check in my code.
I have implemented class which extends ItemKeyedDataSource and provides paging data from room database's data access object (DAO). My DAO's query methods pass lists of data objects (not wrapped by LiveData) to DataSource callbacks.
What is the recommended way to invalidate DataSource after changes occur in it's wrapped database table, for example if changes come from background Service? How automatic data invalidation is implemented in DataSource.Factory<Integer, T> return parameter that DAOs can generate?
Automatic DataSource invalidation can be implemented by hooking InvalidationTracker.Observer to InvalidationTracker.
You can get InvalidationTracker instance from getInvalidationTracker().
I implemented my InvalidationTracker.Observer like this:
public class DataSourceTableObserver extends InvalidationTracker.Observer {
private DataSource dataSource;
public DataSourceTableObserver(#NonNull String tableName) {
super(tableName);
}
#Override
public void onInvalidated(#NonNull Set<String> tables) {
if (dataSource != null) dataSource.invalidate();
}
public void setCurrentDataSource(DataSource source) {
dataSource = source;
}
}
And I'm using it in my inner DataSource.Factory class like this:
public static class Factory implements DataSource.Factory<TvProgram, TvProgram> {
private Context appContext;
private DataSourceTableObserver observer;
private InvalidationTracker tracker;
private int channelId;
public Factory(Context context, int channelId) {
appContext = context.getApplicationContext();
observer = new DataSourceTableObserver(AppDatabase.PROGRAMS_TABLE);
tracker = AppDatabase.getInstance(appContext).getInvalidationTracker();
tracker.addObserver(observer);
this.channelId = channelId;
}
#Override
public DataSource<TvProgram, TvProgram> create() {
EpgDataSource epgDataSource = new EpgDataSource(appContext, channelId);
observer.setCurrentDataSource(epgDataSource);
return epgDataSource;
}
public void cleanUp() {
tracker.removeObserver(observer);
observer = null;
}
}
When DataSourceTableObserver invalidates DataSource, it's Factory inner class creates new DataSource instance with newest data.
I am trying MVP pattern with TDD.
I have the following contract for Model, View And Presenter
Contract Class
interface GithubContract {
interface View {
void displayUsers(List<GurkhaComboDTO> userList);
}
interface Model {
void getUsersAndPromptPresenter(String userName, Presenter presenter);
}
interface Presenter {
void searchUsers(String userName);
void loadUsers(List<GithubUserDTO> userList);
}
}
I am trying to unit test the presenter logic like this :
Test Class
#RunWith(MockitoJUnitRunner.class)
public class GithubPresenterWithMockitoTest {
#Mock
GithubContract.Model mockedModel;
#Test
public void shouldDisplayUsersToScreen() {
//given
final GithubContract.View view = new MockView(); // I have created the mock myself for the view this time.
final GithubContract.Presenter presenter = new GithubPresenter(view, mockedModel);
***********************************************************
// I do not know what to write here
****************************************************
presenter.searchUsers("");
Assert.assertEquals(true, ((MockView) (view)).enoughItems);
}
}
My MockView / VIEW class looks like this :
This is -> Mock class
class MockView implements GithubContract.View {
boolean enoughItems = false;
#Override
public void displayUsers(List<GurkhaComboDTO> userList) {
enoughItems = true;
}
}
My PRESENTER implementation of contract is like this ..
This is -> Real Class
class GithubPresenter implements GithubContract.Presenter {
private GithubContract.View view;
private GithubContract.Model model;
GithubPresenter(GithubContract.View view, GithubContract.Model model) {
this.view = view;
this.model = model;
}
#Override
public void searchUsers(String userName) {
model.getUsersAndPromptPresenter(userName, this);
}
#Override
public void loadUsers(List<GithubUserDTO> data) {
if (data != null) {
if (!data.isEmpty()) {
view.displayUsers(users);
}
}
}
I have the MODEL class Implementation like this :
This is -> Real Class
public class GithubModel implements Model {
#Inject
GithubAPIService apiService;
private Call<GithubUserListDTO> userListCall;
private Context context;
GithubModel(Context context) {
this.context = context;
apiService = Util.getAPIService(); // I am using dagger, retrofit and okhttp3 with GSON to get Objects directly from network call
}
#Override
public void getUsersAndPromptPresenter(final String userName, final GithubContract.Presenter presenter) {
userListCall = apiService.searchGitHubUsers(userName);
if(Util.isInternetConnected(context)) {
userListCall.enqueue(new Callback<GithubUserListDTO>() {
#Override
public void onResponse(Call<GithubUserListDTO> call, Response<GithubUserListDTO> response) {
try {
presenter.loadUsers(response.body().getList());
} catch (Exception ignored) {
Util.log(ignored.getMessage());
}
}
#Override
public void onFailure(Call<GithubUserListDTO> call, Throwable t) {
}
});
}else {
Util.log("No Internet");
}
}
}
Now the real problem part:
I was successfully able to test the presenter with the mock of GithubContract.Model myself, But I want to use Mockito to mock the Model but as my getUsersAndPromptPresenter() method is abstract, returns void, takes parameters and calls back to presenter from an Inner class inside the method.
How can I mock my Model? If I need to bring some change in architecture in order to be able to make it testable, then please suggest it.
You shouldn't pass presenter to Model, Model and Presenter shouldn't be tightly coupled because it prevents model classes from being reusable. Instead provide succesfull and error callbacks(or a composite object that contains both these callbacks). And then you will be able to capture that callback with mockito and call the required one. Also it's very common today to use RxJava, it makes it easier to mock Model classes.
And here is a general good practice: you should avoid to use And/Or words in method names because it indicates that the method is doing more than one thing which is bad
I am creating Android application using MVP pattern.
For that I am using Retrofit 2 and RxJava. App works fine
But in unit testing I am getting weird error.Same test code sometimes passes, sometimes fails.
Error displays with this message
Wanted but not invoked:
albumView.showProgress();
-> at kz.afckairat.kairat.media.AlbumPresenterTest.checkGetPhotoAlbums(AlbumPresenterTest.java:66)
Actually, there were zero interactions with this mock.
Test class
public class AlbumPresenterTest {
enter code here
private MediaService mediaService;
private AlbumView albumView;
private AlbumPresenterImpl photoAlbumPresenter;
#Before
public void setUp() throws Exception {
albumView = mock(AlbumView.class);
mediaService = mock(MediaService.class);
photoAlbumPresenter = new AlbumPresenterImpl(albumView, mediaService, MediaType.PHOTO);
RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() {
#Override
public Scheduler getMainThreadScheduler() {
return Schedulers.immediate();
}
});
}
#After
public void tearDown() {
RxAndroidPlugins.getInstance().reset();
}
#Test
public void checkGetPhotoAlbums() {
List<Album> albums = getAlbumList();
when(mediaService.getPhotoAlbums()).thenReturn(Observable.just(albums));
photoAlbumPresenter.getAlbums();
verify(albumView).showProgress();
verify(albumView).showAlbums(albums);
verify(albumView).hideProgress();
}
#Test
public void checkGetPhotoAlbumError() {
String msg = "Error";
when(mediaService.getPhotoAlbums()).thenReturn(Observable.error(new IOException(msg)));
photoAlbumPresenter.getAlbums();
verify(albumView).showProgress();
verify(albumView).showError(msg);
verify(albumView).hideProgress();
}
private List<Album> getAlbumList() {
List<Album> albums = new ArrayList<>();
Album album = new Album(1, "Test1", "test1.jpg", "01.01.2016", 2);
albums.add(album);
album = new Album(2, "Test2", "test2.jpg", "01.01.2016", 2);
albums.add(album);
return albums;
}
}
Presenter class which is tested
public class AlbumPresenterImpl implements AlbumPresenter {
private AlbumView view;
private MediaType type;
private List<Album> albums;
private MediaService mediaService;
public AlbumPresenterImpl(AlbumView view, MediaService mediaService, MediaType type) {
this.view = view;
this.mediaService = mediaService;
this.type = type;
}
#Override
public void getAlbums() {
Observable<List<Album>> observable;
if (type.equals(MediaType.VIDEO)) {
observable = mediaService.getVideoAlbums();
} else {
observable = mediaService.getPhotoAlbums();
}
observable.doOnSubscribe(view::showProgress)
.doAfterTerminate(view::hideProgress)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(items -> {
albums = items;
view.showAlbums(albums);
}, throwable -> {
view.showError(throwable.getLocalizedMessage());
});
}
#Override
public void onResume() {
if (albums == null) {
getAlbums();
}
}
#Override
public void onDestroy() {
}
}
Why sometimes test don't pass?
Thanks a lot!
=================================
Update
As #Fred wrote problem was in Schedulers
public class RxSchedulersOverrideRule implements TestRule {
private final RxJavaSchedulersHook mRxJavaSchedulersHook = new RxJavaSchedulersHook() {
#Override
public Scheduler getIOScheduler() {
return Schedulers.immediate();
}
#Override
public Scheduler getNewThreadScheduler() {
return Schedulers.immediate();
}
};
private final RxAndroidSchedulersHook mRxAndroidSchedulersHook = new RxAndroidSchedulersHook() {
#Override
public Scheduler getMainThreadScheduler() {
return Schedulers.immediate();
}
};
// Hack to get around RxJavaPlugins.reset() not being public
// See https://github.com/ReactiveX/RxJava/issues/2297
// Hopefully the method will be public in new releases of RxAndroid and we can remove the hack.
private void callResetViaReflectionIn(RxJavaPlugins rxJavaPlugins)
throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Method method = rxJavaPlugins.getClass().getDeclaredMethod("reset");
method.setAccessible(true);
method.invoke(rxJavaPlugins);
}
#Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
#Override
public void evaluate() throws Throwable {
RxAndroidPlugins.getInstance().reset();
RxAndroidPlugins.getInstance().registerSchedulersHook(mRxAndroidSchedulersHook);
callResetViaReflectionIn(RxJavaPlugins.getInstance());
RxJavaPlugins.getInstance().registerSchedulersHook(mRxJavaSchedulersHook);
base.evaluate();
RxAndroidPlugins.getInstance().reset();
callResetViaReflectionIn(RxJavaPlugins.getInstance());
}
};
}
}
Code taken from Github a link!
And in Test class
#Rule
public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule();
It seems you override the main thread scheduler with:
RxAndroidPlugins.getInstance().registerSchedulersHook(new RxAndroidSchedulersHook() {
#Override
public Scheduler getMainThreadScheduler() {
return Schedulers.immediate();
}
});
But from the code, the observables still run on the Schedulers.io() scheduler:
observable.doOnSubscribe(view::showProgress)
.doAfterTerminate(view::hideProgress)
.subscribeOn(Schedulers.io())
// ...
As you may know, the immediate scheduler executes code in the current thread, which I guess since you jump to the io scheduler it's a different one from the one the tests run on.
This will make the test run in one thread and the subscribers/observables in another. This would explain why sometimes the tests pass and sometimes they don't. There's a race condition.
Essential the easiest way is to make sure that at test time you have both observeOn and subscribeOn on Schedulers.immediate() and at run time you have the correct ones, i.e., Schedulers.io() and AndroidSchedulers.mainThread().
You can do this by overriding the schedulers, by passing them as constructors or you could even take a look at this where Dan Lew explains how to use compose to create scheduler transformers. You can then make sure your classes at run time use a proper scheduler transformer and at test time they use some transformer that puts everything on the immediate thread.