I have this mock class:
class MockCategoriesRepository implements CategoriesRepository {
@Override
public LiveData<List<Category>> getAllCategories() {
List<Category> categories = new ArrayList<>();
categories.add(new Category());
categories.add(new Category());
categories.add(new Category());
MutableLiveData<List<Category>> liveData = new MutableLiveData<>();
liveData.setValue(categories);
return liveData;
}
}
and the test:
@Test
public void getAllCategories() {
CategoriesRepository categoriesRepository = new MockCategoriesRepository();
LiveData<List<Category>> allCategories = categoriesRepository.getAllCategories();
}
I want to test List<Category>
for empty.
How can I do it? Can I use Mockito for it?
First, the LiveData should be observed in order to work properly. You can find a utility class at the end of the section to observe your LiveData from test class. Secondly we should add InstantExecutorRule test rule. InstantExecutorRule is a JUnit rule and it comes with androidx.
Unit tests or small tests only verify a very small portion of the app, such as a method or class. End-to-end tests or big tests verify larger parts of the app at the same time, such as a whole screen or user flow. Medium tests are in between and check the integration between two or more units.
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
In this codelab, you use the JUnit framework to write unit tests. To use the framework, you need to add it as a dependency in your app module's build. gradle file. You can now use this library in your app's source code, and Android studio will help to add it to the generated Application Package File (APK) file.
You can do without Mockito, just add the following line to your test:
Assert.assertFalse(allCategories.getValue().isEmpty());
To make it work, you should also add:
testImplementation "android.arch.core:core-testing:1.1.1"
to your app/build.gradle
file and also add the following to the test class:
@Rule
public TestRule rule = new InstantTaskExecutorRule();
It is needed because by default LiveData
operates on its own thread which comes from the Android dependency (not available on pure JVM environment).
So, the whole test should look like:
public class ExampleUnitTest {
@Rule
public TestRule rule = new InstantTaskExecutorRule();
@Test
public void getAllCategories() {
CategoriesRepository categoriesRepository = new MockCategoriesRepository();
LiveData<List<Category>> allCategories = categoriesRepository.getAllCategories();
Assert.assertFalse(allCategories.getValue().isEmpty());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With